先回忆一下多对多的例子:
ManyToManyField.
through_fields
¶
through_fields=('group', 'person')这个参数只能出现在自定义中介表(intermediary model)时。普通情况下,django程序会自动识别中介表中哪两个字段是分别表示要关联的两张表。但也有特例。
Only used when a custom intermediary model is specified. Django will normally determine which fields of the intermediary model to use in order to establish a many-to-many relationship automatically. However, consider the following models:
from django.db import models class Person(models.Model): name = models.CharField(max_length=50) class Group(models.Model): name = models.CharField(max_length=128) members = models.ManyToManyField( Person, through='Membership', through_fields=('group', 'person'), ) class Membership(models.Model): group = models.ForeignKey(Group, on_delete=models.CASCADE) person = models.ForeignKey(Person, on_delete=models.CASCADE) inviter = models.ForeignKey( Person, on_delete=models.CASCADE, related_name="membership_invites", ) invite_reason = models.CharField(max_length=64)
中介表Membership
有两个指向Person
表的外键字段,会产生混淆使django不知道哪个字段是表示多对多关系的。这是,你必须明确指明哪个外键是表示多对多关系的,这就需要通过through_fields参数。
Membership
has two foreign keys to Person
(person
and inviter
), which makes the relationship ambiguous and Django can't know which one to use. In this case, you must explicitly specify which foreign keys Django should use using through_fields
, as in the example above.
下面是环回关系的例子,自己是自己的外键,或者自己和自己是多对多关系。
To create a recursive relationship -- an object that has a many-to-one relationship with itself -- use models.ForeignKey('self', on_delete=models.CASCADE)
.
A many-to-many relationship. Requires a positional argument: the class to which the model is related, which works exactly the same as it does for ForeignKey
, including recursive and lazy relationships.
https://docs.djangoproject.com/zh-hans/2.1/ref/models/fields/#recursive-relationships
https://docs.djangoproject.com/zh-hans/2.1/topics/db/models/#many-to-many-relationships