Skip to content

Commit

Permalink
Allow role assignment queries to use .only
Browse files Browse the repository at this point in the history
  • Loading branch information
AlanCoding committed Jun 20, 2024
1 parent 5a463cd commit d05b0a5
Show file tree
Hide file tree
Showing 2 changed files with 24 additions and 5 deletions.
14 changes: 9 additions & 5 deletions ansible_base/rbac/models.py
Original file line number Diff line number Diff line change
Expand Up @@ -389,11 +389,15 @@ class Meta:
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)

# Cache fields from the associated object_role
if self.object_role_id and not self.object_id:
self.object_id = self.object_role.object_id
self.content_type_id = self.object_role.content_type_id
self.role_definition_id = self.object_role.role_definition_id
# Fields from object_role are cached onto assignment objects, only when creating new assignments
# we must be very careful to avoid referencing deferred attributes to avoid RecursionError
def_fields = self.get_deferred_fields()
if not ({'id', 'object_id', 'object_role_id'} & def_fields):
if self.object_role_id and not self.object_id:
# Cache fields from the associated object_role
self.object_id = self.object_role.object_id
self.content_type_id = self.object_role.content_type_id
self.role_definition_id = self.object_role.role_definition_id


class RoleUserAssignment(AssignmentBase):
Expand Down
15 changes: 15 additions & 0 deletions test_app/tests/rbac/models/test_role_assignments.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
import pytest

from ansible_base.rbac.models import RoleUserAssignment


@pytest.mark.django_db
def test_load_assignment_list(rando, inventory, inv_rd):
assignment = inv_rd.give_permission(rando, inventory)
assert assignment.id in [asmt.id for asmt in RoleUserAssignment.objects.only('id')]


@pytest.mark.django_db
def test_load_assignment_property(rando, inventory, inv_rd):
assignment = inv_rd.give_permission(rando, inventory)
assert assignment.object_id in [int(asmt.object_id) for asmt in RoleUserAssignment.objects.only('object_id')]

0 comments on commit d05b0a5

Please sign in to comment.