模型通过中间模型有两个多对多关系 [英] The model has two many-to-many relations through the intermediate model

查看:49
本文介绍了模型通过中间模型有两个多对多关系的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个模型,它有 2 个独立的 ManyToManyField 关系回到自身

I have a model that has 2 separate ManyToManyField relations back to itself

class Company(models.Model):
    parent          =     models.ManyToManyField("self", through='CompanyParent', through_fields=('company_child', 'company_parent'), related_name='+')
    child           =     models.ManyToManyField("self", through='CompanyParent', through_fields=('company_parent', 'company_child'), related_name='+')

以上在我的本地主机 Django v3.0.2/SQLite 3.8.7.2 上运行良好

The above works fine on my localhost Django v3.0.2/ SQLite 3.8.7.2

要真正发布它,我不得不使用 Django v2.1.15/SQLite 3.7.17,但是在发布的版本中,它排除了以下错误

To actually publish it, I have had to use Django v2.1.15/ SQLite 3.7.17, but with the published version it is chucking out the following errors

companys.Company.child: (fields.E332) 多对多字段中间表不能对称.

companies.Company.child: (fields.E332) Many-to-many fields with intermediate tables must not be symmetrical.

companys.Company.parent: (fields.E332) 多对多字段中间表不能对称.

companies.Company.parent: (fields.E332) Many-to-many fields with intermediate tables must not be symmetrical.

companys.Company: (models.E003) 该模型有两个多对多通过中间模型companys.CompanyParent"建立关系.

companies.Company: (models.E003) The model has two many-to-many relations through the intermediate model 'companies.CompanyParent'.

这是怎么回事?通过向每个模型添加 symmetrical=False 解决了前 2 个问题,但不知道如何解决最终错误?

What's going on here? Solved the first 2 issues by adding symmetrical=False to each model, but no idea how to solve the final error?

推荐答案

您可以查看这个答案设置两个多对多关系.

You can check this answer to set up two many-to-many relations.

上述答案中的一个例子:

An example from the mentioned answer:

class Person(models.Model): 
    name = models.CharField(max_length=127, blank=False)
    to_users = models.ManyToManyField(
        'self', 
        symmetrical=False, 
        related_name='from_users',
        through='Event', 
        through_fields=('from_user', 'to_user'),
    )

class Event(models.Model):
    item = models.ForeignKey(Item, related_name='events')
    from_user = models.ForeignKey(Person, related_name='events_as_giver')
    to_user = models.ForeignKey(Person, related_name='events_as_receiver')

这篇关于模型通过中间模型有两个多对多关系的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆