Reputation: 752
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
Upvotes: 3
Views: 1228
Reputation: 752
I would create my 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.
For example I need added organization to UserGroups:
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)
Upvotes: 2