当关系包含属性时,如何在 Django 中实现多对多关系?
How to implement Many to many relation in django when the relation contain attributes?
我是 django 的初学者,我知道您可以使用 ManyToManyField 来 link 两个模型,例如 author-post 用户组。
所以我在我的 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 字段,我就不必创建第三个 class '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.
您模型中的组 class 应如下所示:
class Group(models.Model):
# group fields
# ...
users = models.ManyToManyField(User, through='GroupMember')
我是 django 的初学者,我知道您可以使用 ManyToManyField 来 link 两个模型,例如 author-post 用户组。
所以我在我的 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 字段,我就不必创建第三个 class '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.
您模型中的组 class 应如下所示:
class Group(models.Model):
# group fields
# ...
users = models.ManyToManyField(User, through='GroupMember')