简体   繁体   English

Django的ManyToManyField之间指向的两个对象

[英]Django ManyToManyField between 2 objects that point to one another

In my project, I have 2 models with a ManyToMany field that point to each other. 在我的项目中,我有2个模型,它们具有指向彼此的ManyToMany字段。 In this case, I have Elections and Candidates. 在这种情况下,我有选举和候选人。 The idea is that an Election can have multiple Candidates and that a Candidate can also be part of multiple elections (One 'Candidate' is only one person). 这个想法是,一个选举可以有多个候选人,一个候选人也可以是多个选举的一部分(一个“候选人”只有一个人)。

I have the following: 我有以下内容:

project/elections/models.py 项目/选/ models.py

from candidates.models import Candidate

class Election(models.Model):
    candidates = models.ManyToManyField(Candidate)
    ...

project/candidates/models.py 项目/候选人/ models.py

from elections.models import Election
    elections = models.ManyToManyField(Election)
    ...

When I try to run any command (makemigrations, runserver, etc.) I get a circular dependency between Election and Candidate which crashes. 当我尝试运行任何命令(makemigrations,runserver等)时,我在Election和Candidate之间遇到了循环依赖关系,从而导致崩溃。 I have the models in different apps as a coding practice. 我将不同应用程序中的模型作为编码实践。

Should I: 我是不是该:

  1. Move both models to one app and one file 将两种模型都移动到一个应用程序和一个文件中

  2. Not have the models pointing to each other (how would I then accomplish my goal?) 模型之间没有指向彼此(我将如何实现目标?)

  3. Do something different 做一些不同的事情

To avoid circular dependency don't import the models, use strings instead, and include the applications name as namespace 为避免循环依赖,请不要导入模型,而应使用字符串,并将应用程序名称包含为名称空间

project/elections/models.py 项目/选/ models.py

class Election(models.Model):
    candidates = models.ManyToManyField('candidates.Candidate')

Update 更新

As the django docs points out, you only need to declare the relation on one of the models https://docs.djangoproject.com/es/2.1/topics/db/models/#many-to-many-relationships 正如django docs指出的那样,您只需要在以下模型之一上声明关系https://docs.djangoproject.com/es/2.1/topics/db/models/#many-to-many-relationships

It doesn't matter which model has the ManyToManyField, but you should only put it in one of the models – not both. 哪个模型具有ManyToManyField无关紧要,但是您只应将其放在其中一个模型中,而不要同时放在两个模型中。

You do not need to do this . 不需要这样做 A many-to-many field is already bidirectional. 多对多字段已经是双向的。 Just define it on one side, and use the reverse relation. 只需把它定义在一边 ,并使用反向关系。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM