python – Django:有没有办法在与包含ManyToManyField的模型不同的应用程序中的ManyToManyField中使用“直通”模型?

前端之家收集整理的这篇文章主要介绍了python – Django:有没有办法在与包含ManyToManyField的模型不同的应用程序中的ManyToManyField中使用“直通”模型?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
可以说我有两个 django应用程序:

>比赛 – 将处理比赛数据
>条目 – 将处理与参赛者进入比赛相关的功能

在比赛应用程序中,我有一个模型代表比赛的一部分:

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 …语句,以便它们有效?当我输入import语句时,例如来自entries.models import Entry我从syncdb忽略这些应用程序的模型(因为导入是循环的)或当我删除其中一个或两个时,我得到验证错误

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

我理解为什么会发生这种情况,但我不知道如何更改它,以便它可以工作(不需要将Entry模型移动到竞赛应用程序中,我真的不想这样做).

解决方法

好像我找到了一个答案,它更加一致:)

Django documentation on the ForeignKey class说:

To refer to models defined in another
application,you can explicitly
specify a model with the full
application label. For example,if the
Manufacturer model above is defined in
another application called production,
you’d need to use:

class Car(models.Model):
    manufacturer = models.ForeignKey('production.Manufacturer')

This sort of reference can be useful when resolving circular import dependencies between two applications.

原文链接:/python/186097.html

猜你在找的Python相关文章