【问题标题】:how to add a field to User.groups.through in Django?如何在 Django 中向 User.groups.through 添加字段?
【发布时间】:2020-08-15 08:33:58
【问题描述】:

我想将我的字段添加到表 user_user_group。 我可以将字段添加到表组,但我不能将字段添加到用户模型中的多对多组字段。我使用猴子解决方案将字段添加到组模型,但它不适用于用户模型中的多对多组字段。

此代码有效:

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

此代码不起作用:

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

你有什么解决办法吗?

解决这个解决方案或告诉我其他解决方案

【问题讨论】:

    标签: django django-models


    【解决方案1】:

    我将创建我的用户模型,该模型使用通过参数指定我的自定义表来使用 ManyToManyField 定义它与 Group 的关系。 我也不会尝试将字段直接添加到 Group 表中。

    例如,我需要将组织添加到用户组:

    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)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-08-08
      • 1970-01-01
      • 1970-01-01
      • 2012-01-26
      • 2013-05-14
      • 2010-12-25
      • 1970-01-01
      • 2020-11-26
      相关资源
      最近更新 更多