我有一个模型,它有两个独立的ManyToManyField关系
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上运行良好
为了真正发布它,我不得不使用Django v2.1.15/SQLite 3.7.17,但是发布的版本中出现了以下错误
companies.Company.child: (fields.E332) Many-to-many fields with intermediate tables must not be symmetrical.
companies.Company.parent: (fields.E332) Many-to-many fields with intermediate tables must not be symmetrical.
companies.Company: (models.E003) The model has two many-to-many relations through the intermediate model 'companies.CompanyParent'.
这是怎么回事?通过向每个模型添加symmetrical=False
解决了前两个问题,但不知道如何解决最终错误
您可以选中this answer设置两个多对多关系
上述答案中的一个例子:
如果任何人遇到同一问题;以上是答案,但我认为在对自己的项目进行必要的更改后,我会稍微扩展一下
如果您希望在同一个模型中有多对多,并且您使用的是2.2a1之后的Django版本,那么最好的方法就是我在问题中详述的方法;两种不同的模型,您可以轻松调用视图或模板;例如—
但是,在2.2a1之前,您将遇到问题。对我来说,这是因为在cPanel上,由于使用了较旧的SQLite 3.7.17,我不得不使用Django v2.1.15。这意味着您只能有一个ManyToManyField(见上文),并使用过滤器获取第二个manytomany>;您只能在views.py中执行此操作
希望这是有道理的
相关问题 更多 >
编程相关推荐