在 Django 中,中间模型是否需要与目标模型属于同一个文件?

In Django, does the intermediate model need to belong in the same file as the target model?

当运行进行迁移时,每当我定义了 ManyToManyField 的模型位于与模型不同的文件中时,我目前都会收到此 lazy reference ValueError我的目标。但是,当我将两个模型放在同一个文件中时,我能够成功 运行 迁移。

  1. 为什么会出现这个错误?
  2. 是否可以将模型(community.py 和 community_member.py)分成单独的文件?

ValueError: contains a lazy reference to fitness.communitymember, but app 'fitness' doesn't provide model 'communitymember'.

我的目录结构如下所示:

my_app
  |----fitness
       |----user.py
       |----community.py
       |----community_member.py

community.py

class Community(models.Model):
    id = models.AutoField(
        primary_key=True,
    )
    owner = models.ForeignKey(
        User,
    )
    members = models.ManyToManyField(
        User,
        through='CommunityMember',
        through_fields=('community', 'member')
    )

    class Meta:
        db_table = 'Communities'

community_member.py

class CommunityMember(models.Model):
    community = models.ForeignKey(
        Community,
        db_column='community_id'
    )
    member = models.ForeignKey(
        User,
        db_column='member_id',
    )

    class Meta:
        db_table = 'Community_Members'

settings.py

INSTALLED_APPS = [
    'my_app.fitness'
]           

如果我将 community_members.py 的内容放在 community.py 中,迁移会成功执行,但是我不知道为什么。

急了,真不知道你为什么要拆分模型,但你非要拆分,那肯定是有原因的。默认的 Django 应用程序必须包含一个 models.py 文件。 ValueError 是因为 Django 无法找到你所有的模型定义,它不知道去哪里寻找这些模型。如果您坚持这样做(我个人不建议只使用两种型号),您应该按照文档的建议进行操作:https://docs.djangoproject.com/en/1.11/topics/db/models/#organizing-models-in-a-package