為了建立鄰區關係,有不多建立表,利用ManyToManyField("self")
先回憶一下多對多的例子:
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
下面是環回關係的例子,自己是自己的外來鍵,或者自己和自己是多對多關係。
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