【问题标题】:How to implement Many to many relation in django when the relation contain attributes?当关系包含属性时,如何在django中实现多对多关系?
【发布时间】:2020-08-16 12:54:03
【问题描述】:

我是 django 的初学者,我知道您可以使用 ManyToManyField 来链接两个模型,例如作者-发布用户组。 所以我在我的 UML 中有这种关系@

如何在我的代码中实现这一点? 我的镜头是这样的

class User(models.Model):
# user fields

class Group(models.Model):
     # group fields

class GroupMember(models.Model):
    group = models.ForeignKey(Group, on_delete=models.DO_NOTHING, db_index=True)
    user = models.ForeignKey(User, on_delete=models.DO_NOTHING, db_index=True)
    IsAdmin = models.BooleanField(default=False, verbose_name='Est un admin')

    class Meta:
        unique_together = (("group", "user"),)

我想使用 ManyToManyFields 以便在它们之间进行引用(如果我没有 IsAdmin 字段,我不必创建第三个类 'GroupMember')

【问题讨论】:

    标签: django django-models many-to-many uml


    【解决方案1】:

    您可以从官方文档中找到示例:https://docs.djangoproject.com/en/3.0/topics/db/models/#extra-fields-on-many-to-many-relationships

    中间模型与 ManyToManyField 使用关联 through 参数指向将作为 中介。

    你的模型中的 Group 类应该是这样的:

    class Group(models.Model):
        # group fields
        # ...
        users = models.ManyToManyField(User, through='GroupMember')
    

    【讨论】:

      猜你喜欢
      • 2014-12-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-04-05
      • 1970-01-01
      • 1970-01-01
      • 2019-10-25
      • 1970-01-01
      相关资源
      最近更新 更多