You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Django多对多关联报错:中间模型BlogContributor未安装

Django 多对多关联 through 模型未安装报错解决

这是我在Stack Overflow的第一篇帖子,若有需要改进之处请告知。我尝试重启一个旧项目,该项目包含blog和authentication两个应用。

blog.models 代码

class BlogContributor(models.Model):
    contributor = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
    blog = models.ForeignKey(Blog, on_delete=models.CASCADE)
    contribution = models.CharField(max_length=255, blank=True)

    class Meta:
        unique_together = ("contributor", "blog")

authentication.models 代码

class User(AbstractUser):
    CREATOR = "CREATOR"
    SUBSCRIBER = "SUBSCRIBER"

    ROLE_CHOICES = (
        (CREATOR, "Créateur"),
        (SUBSCRIBER, "Abonné"),
    )
    profile_photo = models.ImageField(verbose_name="photo de profil")
    role = models.CharField(max_length=30, choices=ROLE_CHOICES, verbose_name="rôle")

    follows = models.ManyToManyField(
        "self",
        limit_choices_to={"role": CREATOR},
        symmetrical=False,
        verbose_name="suit",
    )
    blogs = models.ManyToManyField(
        "self",
        through="BlogContributor",
        related_name="contributors",
    )

报错信息

authentication.User.blogs: (fields.E331)

Field specifies a many-to-many relation through model 'BlogContributor', which has not been installed.

尝试过的解决方法

  • 在authentication.models中导入BlogContributor,无效
  • 在authentication的__init__.py中导入BlogContributor,触发新错误:
raise AppRegistryNotReady("Apps aren't loaded yet.")

django.core.exceptions.AppRegistryNotReady: Apps aren't loaded yet. 

解决办法

1. 用完整应用模型路径引用through模型

修改authentication.models里的blogs字段,把through参数改成带应用名的完整路径:

blogs = models.ManyToManyField(
    "self",
    through="blog.BlogContributor",
    related_name="contributors",
)

Django会通过这个完整路径定位到模型,无需直接导入,避开应用加载顺序冲突的问题。

2. 调整INSTALLED_APPS加载顺序

打开项目的settings.py,确保blog在authentication之前加入INSTALLED_APPS:

INSTALLED_APPS = [
    # 其他默认应用...
    'blog',
    'authentication',
]

这样Django会优先加载blog应用的模型,authentication引用时就能找到BlogContributor了。

3. 删除__init__.py中的模型导入

之前在authentication/__init__.py里导入模型的操作会破坏Django的应用加载流程,直接删掉该导入语句即可解决AppRegistryNotReady错误。


内容的提问来源于stack exchange,提问作者MarineBap

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.17 00:55:26