Skip to content

Commit

Permalink
Merge pull request #390 from markkuleinio/field_name_lookup
Browse files Browse the repository at this point in the history
Add custom model name lookup to fix #389
  • Loading branch information
zachmoody committed Dec 4, 2021
2 parents 01a390f + 3d7bee0 commit c702fd1
Show file tree
Hide file tree
Showing 4 changed files with 27 additions and 4 deletions.
13 changes: 10 additions & 3 deletions pynetbox/core/response.py
Original file line number Diff line number Diff line change
Expand Up @@ -349,9 +349,16 @@ def _parse_values(self, values):
values within.
"""

def list_parser(list_item):
def list_parser(key_name, list_item):
if isinstance(list_item, dict):
return self.default_ret(list_item, self.api, self.endpoint)
lookup = getattr(self.__class__, key_name, None)
if not isinstance(lookup, list):
# This is *list_parser*, so if the custom model field is not
# a list (or is not defined), just return the default model
return self.default_ret(list_item, self.api, self.endpoint)
else:
model = lookup[0]
return model(list_item, self.api, self.endpoint)
return list_item

for k, v in values.items():
Expand All @@ -370,7 +377,7 @@ def list_parser(list_item):
self._add_cache((k, v))

elif isinstance(v, list):
v = [list_parser(i) for i in v]
v = [list_parser(k, i) for i in v]
to_cache = list(v)
self._add_cache((k, to_cache))

Expand Down
1 change: 1 addition & 0 deletions pynetbox/models/users.py
Original file line number Diff line number Diff line change
Expand Up @@ -22,4 +22,5 @@ def __str__(self):


class Permissions(Record):
users = [Users]
constraints = JsonField
7 changes: 6 additions & 1 deletion tests/fixtures/users/permission.json
Original file line number Diff line number Diff line change
@@ -1,4 +1,9 @@
{
"id": 1,
"name": "permission1"
"name": "permission1",
"users": [
{
"username": "user1"
}
]
}
10 changes: 10 additions & 0 deletions tests/test_users.py
Original file line number Diff line number Diff line change
Expand Up @@ -95,3 +95,13 @@ class GroupsTestCase(Generic.Tests):

class PermissionsTestCase(Generic.Tests):
name = "permissions"

@patch(
"requests.sessions.Session.get",
return_value=Response(fixture="users/permission.json"),
)
def test_username(self, _):
permission = nb.permissions.get(1)
self.assertEqual(len(permission.users), 1)
user = permission.users[0]
self.assertEqual(str(user), "user1")

0 comments on commit c702fd1

Please sign in to comment.