Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add custom model name lookup to fix #389 #390

Merged
merged 8 commits into from
Dec 4, 2021
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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")