为了创建邻区关系,有不多建立表,利用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, 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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值