姜戈:有没有办法让事情“通过”?与包含 ManyToManyField 的模型不同的应用程序中的 ManyToManyField 中的模型?
假设我有两个 django 应用程序:
- competitions - 将处理比赛数据
- entries - 将处理与让竞争对手参加比赛相关的功能
在竞赛应用程序中,我有一个模型代表竞赛的一部分:
class Division(models.Model):
competition = models.ForeignKey(Competition)
discipline = models.CharField(max_length=1, choices=DISCIPLINE_CHOICES)
age_group = models.ForeignKey(AgeGroup)
participants = models.ManyToManyField(Competitor, through='Entry')
我想将 Entry 模型放入条目应用程序中:
class Entry(models.Model):
division = models.ForeignKey('Division')
competitor = models.ForeignKey(Competitor)
withdrawn = models.BooleanField(default=False)
如何解决 from ... import ... 语句,以便它们起作用?当我输入诸如 fromentries.models import Entry
之类的导入语句时,我会从这些应用程序中获取被syncdb忽略的模型(因为导入是循环的),或者当我删除其中一个或两个时,我会得到验证错误:
错误:一个或多个模型没有 验证:entry.entry:'除法' 与模型部门有关系, 尚未安装或 是抽象的。竞赛.分组: “参与者”指定 m2m 通过模型条目建立关系,其中 尚未安装
我明白为什么会发生这种情况,但我不知道如何更改它,以便它可以工作(而不需要将 Entry 模型移动到竞赛应用程序中,我真的不想这样做)。
Lets say I have two django apps:
- competitions - which will handle competition data
- entries - which will handle functionality relating to entering competitors into competitions
In the competitions app I have a model which represents a section of a competition:
class Division(models.Model):
competition = models.ForeignKey(Competition)
discipline = models.CharField(max_length=1, choices=DISCIPLINE_CHOICES)
age_group = models.ForeignKey(AgeGroup)
participants = models.ManyToManyField(Competitor, through='Entry')
I want to put the Entry model in the entries app:
class Entry(models.Model):
division = models.ForeignKey('Division')
competitor = models.ForeignKey(Competitor)
withdrawn = models.BooleanField(default=False)
How do I solve the from ... import ... statements, so that they work? When I put in import statements such as from entries.models import Entry
I get the models from these apps ignored by syncdb (because the imports are circular) or when I remove one or both of them I get validation errors:
Error: One or more models did not
validate: entries.entry: 'division'
has a relation with model Division,
which has either not been installed or
is abstract. competitions.division:
'participants' specifies an m2m
relation through model Entry, which
has not been installed
I understand why this happens, but I have no idea how to change this, so that it works (without resorting to moving the Entry model into the competitions app, which I really don't want to do).
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
看来我找到了一个更一致的答案:)
关于ForeignKey类的Django文档说:
It seems like I've found an answer, which works more consistently :)
The Django documentation on the ForeignKey class says:
有时,django.db.models.get_model 有助于解决循环导入问题。在您的示例中,尝试正常导入
Entry
并将Entry
中的division
FK 定义更改为:sometimes,
django.db.models.get_model
helps to work around circular imports. In your example, try to importEntry
normally and chage thedivision
FK definition inEntry
to this: