diff --git a/ansible_base/rbac/models.py b/ansible_base/rbac/models.py index c0aaa7d4c..ac9e47c19 100644 --- a/ansible_base/rbac/models.py +++ b/ansible_base/rbac/models.py @@ -389,14 +389,14 @@ class Meta: app_label = 'dab_rbac' abstract = True - 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 + def save(self, *args, **kwargs): + if not self.id: # usually only new objects can be saved, but super needs to do error handling + 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 + return super().save(*args, **kwargs) class RoleUserAssignment(AssignmentBase): diff --git a/test_app/tests/rbac/models/test_role_assignments.py b/test_app/tests/rbac/models/test_role_assignments.py new file mode 100644 index 000000000..234812bc0 --- /dev/null +++ b/test_app/tests/rbac/models/test_role_assignments.py @@ -0,0 +1,17 @@ +import pytest + +from ansible_base.rbac.models import RoleUserAssignment + + +@pytest.mark.django_db +def test_load_assignment_list(rando, inventory, inv_rd, global_inv_rd): + assignment = inv_rd.give_permission(rando, inventory) + global_inv_rd.give_global_permission(rando) + 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, global_inv_rd): + assignment = inv_rd.give_permission(rando, inventory) + global_inv_rd.give_global_permission(rando) + assert str(assignment.object_id) in [asmt.object_id for asmt in RoleUserAssignment.objects.only('object_id')]