gpt4 book ai didi

python - Django:有没有办法让 ManyToManyField 中的 "through"模型与包含 ManyToManyField 的模型在不同的应用程序中?

转载 作者:太空狗 更新时间:2023-10-29 20:37:36 26 4
gpt4 key购买 nike

假设我有两个 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 ... 语句,使它们起作用?当我输入诸如 from 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 - Django:有没有办法让 ManyToManyField 中的 "through"模型与包含 ManyToManyField 的模型在不同的应用程序中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1970365/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com