Django 1.8 迁移:django_content_type 不存在

Django 1.8 migrate: django_content_type does not exist

我刚刚将我的 django 从 1.7.1 升级到 1.8.4。我尝试 运行 python manage.py migrate 但出现此错误:

django.db.utils.ProgrammingError: relation "django_content_type" does not exist

我删除了我的数据库,创建了一个新数据库,然后再次 运行 命令。但我得到了同样的错误。我错过了什么吗?我需要做些什么来升级我的 django 吗?

编辑: 我降级回 1.7.1 并且它有效。有没有办法为 1.8.4 修复它?

从您的应用程序中删除所有迁移文件夹并删除数据库,然后迁移您的数据库......

如果这不起作用,请从数据库中删除 django_migration table 并在 django_content_type table ALTER TABLE django_content_type ADD COLUMN name character varying(50) NOT NULL DEFAULT 'anyName'; 中添加 "name" 列,然后运行$ python manage.py migrate --fake-initial

嗯,我发现了问题。我安装了 auditlog 作为我的应用程序之一。我将其删除并迁移正常。

这是我found/did。我正在使用 django 1.8.13 和 python 2.7。 Sqlite 没有出现该问题。它确实发生在 PostgreSQL 上。

我有一个使用 GenericForeignKey(依赖于 Contenttypes)的应用程序。我有另一个应用程序,它的模型通过 GenericForeignKey 链接到第一个应用程序。如果我 运行 为这两个应用程序进行迁移,那么迁移就可以了。

我在尝试从头开始迁移我们的模型时遇到了同样的问题(尤其是在测试构建时)。经过进一步调查,我们发现我们有与 ContentTypes 模型相关的自定义代码,该模型与 django_content_type table:

相关联
staff_content_types = ContentType.objects.filter(model__in=ACCOUNT_STAFF_APPS)

然后,在我们将访问 staff_content_types 变量的后续代码中,它将抛出 django.db.utils.ProgrammingError: Table 'django_content_type' doesn't exist 消息。显然,它试图访问尚未构建的 django_content_type table。我们的代码基于我们的数据已经设置的上下文。

因此,至少有 2 种可能的解决方法。这个想法是 运行 我们的自定义 ContentType 相关逻辑只有当我们的网站已经有数据时(在迁移阶段之后):

  1. 捕获迁移过程中发生的错误并忽略它:

    from django.db.utils import ProgrammingError
    
    try:
        for content_type in staff_content_types:
            # Our custom codes here.
    except ProgrammingError:
        pass
    
  2. 仅当django_content_type table存在(即迁移后的状态)时才继续:

    from django.db import connection
    
    if 'django_content_type' in connection.introspection.table_names():
        for content_type in staff_content_types:
            # Our custom codes here.
    

同样,使用 Django ContentType objects/table 的第 3 方应用程序可能有类似的问题。因此,您要么禁用它们,要么要求它们的作者使用此处建议的想法修补他们的贡献应用程序。

我删除了数据库并重建了它,然后在 PyCharm 终端 py manage.py makemigrationspy manage.py migrate 中解决了这个问题。我想原因是table django_content_type是django的table,如果misssed无法迁移,只好drop掉数据库重建。

首先尝试迁移 contenttypes,然后是 Django 中包含的其余模型,然后是您自己的模型:

./manage.py migrate contenttypes
./manage.py migrate
./manage.py makemigrations <YOUR APP>
./manage.py migrate --fake