how to add a field to User.groups.through in Django?

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.

this code work:

Group.add_to_class('type', models.IntegerField(choices=RoleType.choices, default=RoleType.ADMIN))

this code does not work:

User.groups.through.add_to_class('organization', models.ForeignKey(Organization, on_delete=models.CASCADE, null=True))

are you have any solution?

solve this solution or tell me other solution

1 Like

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.)

Ken

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?

is it your solution like this?

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)
1 Like

Yea, that’s the basic idea I was thinking of - I’m not immediately aware of any problems this would cause, but I could well be wrong.

Ken

Thanks,
excellent. I will use this solution.