我是 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”)
最佳答案
您可以在官方文档中找到示例:https://docs.djangoproject.com/en/3.0/topics/db/models/#extra-fields-on-many-to-many-relationships
The intermediate model is associated with the ManyToManyField using the through argument to point to the model that will act as an intermediary.
模型中的 Group 类应该类似于:
class Group(models.Model):
# group fields
# ...
users = models.ManyToManyField(User, through='GroupMember')
关于django - 当关系包含属性时,如何在django中实现多对多关系?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61552556/