Hi! How are you guys? I’m kinda new here, but I came to see if anyone could help me with something i’m struggling with… My problem is very simple. I’ll describe the scenario: My intermediate model that joins User and Permission models:
class UsersPermissions(models.Model):
user = models.ForeignKey(User, on_delete=models.CASCADE, verbose_name='ID Usuário')
permission = models.ForeignKey(Permission, on_delete=models.CASCADE, verbose_name='ID Permissão')
client = models.ForeignKey(Client, on_delete=models.CASCADE, verbose_name='ID Cliente')
class Meta:
db_table = 'users_permissions'
constraints = [
UniqueConstraint(fields=['user', 'permission', 'client'], name='unique_user_permission_client')
]
Just it. I just included a third foreign key to link with the Client model. The code that simulates the problem:
u = User.objects.get(pk=1)
p = Permission.objects.get(pk=56)
c = Client.objects.get(pk=2)
res = u.permissions.add(p, through_defaults={'client': c})
u.save()
Scenario:
-
I try to create a UsersPermissions register on database, where user_id = 1, permission_id = 56 and client_id = 2. The register is created successfully.
-
Than, I try to create a UsersPermissions register again, but with a different client_id. Example: user_id = 1, permission_id = 56 and client_id = 1. The register is not created, and no error or messages show up.
Thats it. This is the error. I can’t find a solution to this, as it is so simple and I get no errors. Notes:
- Is valid to remember that my constraint allow the duplicity of user_id and permission_id. It just locks the duplicity of the 3 foreign keys.
- I have no more rules beyond that scenario. You can replicate it at your own code if you want. I’m using the through prop on my User model to link to the UsersPermissions model.