I want to add my field to the table user_user_group. I can add a field to table groups but I can not add a field to the many-to-many group field in the user model. I use a monkey solution for add field to groups model but it does not work for many-to-many group field in the user model.
If I were faced with this type of situation, I would create my own User model that defines its relationship with Group with a ManyToManyField using the through parameter to specify my custom table.
I also wouldn’t try to add fields directly to the Group table, I’d create a OneToOne relationship with additional attribute fields.
(I really don’t like monkey-patches, especially when it comes to core. You never know when it’s going to come back to bite you.)
Thanks
but this solution Complicates my code because I should override the Django permission manager. For example, overrides function get user groups and etc. Maybe I did not understand your solution. can Do you explain more this solution by code or another way?
class User(AbstractUser):
groups = models.ManyToManyField(
Group,
verbose_name=_('groups'),
blank=True,
help_text=_(
'The groups this user belongs to. A user will get all permissions '
'granted to each of their groups.'
),
related_name="user_set",
related_query_name="user",
through="UserGroups"
)
class UserGroups(models.Model):
user = models.ForeignKey(User, on_delete=models.CASCADE)
group = models.ForeignKey(Group, on_delete=models.CASCADE)
organization = models.ForeignKey(Organization, on_delete=models.CASCADE, null=True)