【问题标题】:"django.db.utils.ProgrammingError: relation "app_user" does not exist" during manage.py test“django.db.utils.ProgrammingError:关系“app_user”不存在”在manage.py测试期间
【发布时间】:2015-10-03 17:31:45
【问题描述】:

我的设置:

  • Django 1.8.3
  • Python 2.7.10
  • Ubuntu 14.04
  • django-two-factor-auth==1.2.0

我在运行python manage.py test 时收到以下错误:

Traceback (most recent call last):
  File "/src/venv/bin/django-admin.py", line 5, in <module>
    management.execute_from_command_line()
  File "/src/venv/lib/python2.7/site-packages/django/core/management/__init__.py", line 338, in execute_from_command_line
    utility.execute()
  File "/src/venv/lib/python2.7/site-packages/django/core/management/__init__.py", line 330, in execute
    self.fetch_command(subcommand).run_from_argv(self.argv)
  File "/src/venv/lib/python2.7/site-packages/django/core/management/commands/test.py", line 30, in run_from_argv
    super(Command, self).run_from_argv(argv)
  File "/src/venv/lib/python2.7/site-packages/django/core/management/base.py", line 393, in run_from_argv
    self.execute(*args, **cmd_options)
  File "/src/venv/lib/python2.7/site-packages/django/core/management/commands/test.py", line 74, in execute
    super(Command, self).execute(*args, **options)
  File "/src/venv/lib/python2.7/site-packages/django/core/management/base.py", line 444, in execute
    output = self.handle(*args, **options)
  File "/src/venv/lib/python2.7/site-packages/django/core/management/commands/test.py", line 90, in handle
    failures = test_runner.run_tests(test_labels)
  File "/src/venv/lib/python2.7/site-packages/django/test/runner.py", line 210, in run_tests
    old_config = self.setup_databases()
  File "/src/venv/lib/python2.7/site-packages/django/test/runner.py", line 166, in setup_databases
    **kwargs
  File "/src/venv/lib/python2.7/site-packages/django/test/runner.py", line 370, in setup_databases
    serialize=connection.settings_dict.get("TEST", {}).get("SERIALIZE", True),
  File "/src/venv/lib/python2.7/site-packages/django/db/backends/base/creation.py", line 368, in create_test_db
    test_flush=not keepdb,
  File "/src/venv/lib/python2.7/site-packages/django/core/management/__init__.py", line 120, in call_command
    return command.execute(*args, **defaults)
  File "/src/venv/lib/python2.7/site-packages/django/core/management/base.py", line 444, in execute
    output = self.handle(*args, **options)
  File "/src/venv/lib/python2.7/site-packages/django/core/management/commands/migrate.py", line 179, in handle
    created_models = self.sync_apps(connection, executor.loader.unmigrated_apps)
  File "/src/venv/lib/python2.7/site-packages/django/core/management/commands/migrate.py", line 317, in sync_apps
    cursor.execute(statement)
  File "/src/venv/lib/python2.7/site-packages/django/db/backends/utils.py", line 65, in execute
    return self.cursor.execute(sql, params)
  File "/src/venv/lib/python2.7/site-packages/django/db/utils.py", line 97, in __exit__
    six.reraise(dj_exc_type, dj_exc_value, traceback)
  File "/src/venv/lib/python2.7/site-packages/django/db/backends/utils.py", line 63, in execute
    return self.cursor.execute(sql)
django.db.utils.ProgrammingError: relation "app_user" does not exist

当我在 django/db/backends/utils.py 的第 62 行删除 print(sql) 语句时,我得到以下输出:

CREATE DATABASE "test_dev"

            SELECT c.relname, c.relkind
            FROM pg_catalog.pg_class c
            LEFT JOIN pg_catalog.pg_namespace n ON n.oid = c.relnamespace
            WHERE c.relkind IN ('r', 'v')
                AND n.nspname NOT IN ('pg_catalog', 'pg_toast')
                AND pg_catalog.pg_table_is_visible(c.oid)
CREATE TABLE "django_migrations" ("id" serial NOT NULL PRIMARY KEY, "app" varchar(255) NOT NULL, "name" varchar(255) NOT NULL, "applied" timestamp with time zone NOT NULL)

            SELECT c.relname, c.relkind
            FROM pg_catalog.pg_class c
            LEFT JOIN pg_catalog.pg_namespace n ON n.oid = c.relnamespace
            WHERE c.relkind IN ('r', 'v')
                AND n.nspname NOT IN ('pg_catalog', 'pg_toast')
                AND pg_catalog.pg_table_is_visible(c.oid)
SAVEPOINT "s140275211773760_x1"
CREATE TABLE "distributedlock_lock" ("id" serial NOT NULL PRIMARY KEY, "key" varchar(255) NOT NULL, "value" varchar(255) NOT NULL, "timestamp" timestamp with time zone NULL)
RELEASE SAVEPOINT "s140275211773760_x1"
SAVEPOINT "s140275211773760_x2"
CREATE TABLE "djkombu_queue" ("id" serial NOT NULL PRIMARY KEY, "name" varchar(200) NOT NULL UNIQUE)
RELEASE SAVEPOINT "s140275211773760_x2"
SAVEPOINT "s140275211773760_x3"
CREATE TABLE "djkombu_message" ("id" serial NOT NULL PRIMARY KEY, "visible" boolean NOT NULL, "sent_at" timestamp with time zone NULL, "payload" text NOT NULL, "queue_id" integer NOT NULL)
RELEASE SAVEPOINT "s140275211773760_x3"
SAVEPOINT "s140275211773760_x4"
CREATE TABLE "otp_static_staticdevice" ("id" serial NOT NULL PRIMARY KEY, "user_id" integer NOT NULL, "name" varchar(64) NOT NULL, "confirmed" boolean NOT NULL)
RELEASE SAVEPOINT "s140275211773760_x4"
SAVEPOINT "s140275211773760_x5"
CREATE TABLE "otp_static_statictoken" ("id" serial NOT NULL PRIMARY KEY, "device_id" integer NOT NULL, "token" varchar(16) NOT NULL)
RELEASE SAVEPOINT "s140275211773760_x5"
SAVEPOINT "s140275211773760_x6"
CREATE TABLE "otp_totp_totpdevice" ("id" serial NOT NULL PRIMARY KEY, "user_id" integer NOT NULL, "name" varchar(64) NOT NULL, "confirmed" boolean NOT NULL, "key" varchar(80) NOT NULL, "step" smallint NOT NULL CHECK ("step" >= 0), "t0" bigint NOT NULL, "digits" smallint NOT NULL CHECK ("digits" >= 0), "tolerance" smallint NOT NULL CHECK ("tolerance" >= 0), "drift" smallint NOT NULL, "last_t" bigint NOT NULL)
RELEASE SAVEPOINT "s140275211773760_x6"
CREATE INDEX "djkombu_queue_name_1c24e49fd475ad53_like" ON "djkombu_queue" ("name" varchar_pattern_ops)
ALTER TABLE "djkombu_message" ADD CONSTRAINT "djkombu_message_queue_id_12778caea7843dd_fk_djkombu_queue_id" FOREIGN KEY ("queue_id") REFERENCES "djkombu_queue" ("id") DEFERRABLE INITIALLY DEFERRED
CREATE INDEX "djkombu_message_46cf0e59" ON "djkombu_message" ("visible")
CREATE INDEX "djkombu_message_df2f2974" ON "djkombu_message" ("sent_at")
CREATE INDEX "djkombu_message_75249aa1" ON "djkombu_message" ("queue_id")
ALTER TABLE "otp_static_staticdevice" ADD CONSTRAINT "otp_static_staticdevice_user_id_39a61f1bd3ec970d_fk_app_user_id" FOREIGN KEY ("user_id") REFERENCES "ff_user" ("id") DEFERRABLE INITIALLY DEFERRED

所以我很清楚,在设置测试数据库时我的测试崩溃了。具体来说,在 otp_static_staticdevice 表和我的应用程序的 app_user 表之间创建外键约束的尝试失败。

我的直接问题是,为什么 django 在我的应用程序表之前创建 OTP 表?我的假设是 OTP 应用程序首先列在我的 INSTALLED_APPS 中。但事实并非如此:

INSTALLED_APPS = [
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.sites',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'django.contrib.admin',
    'django.contrib.humanize',
    'app',
    ...
    'django_otp',
    'django_otp.plugins.otp_static',
    'django_otp.plugins.otp_totp',
    'two_factor',
    ...
]

接下来,我查看django/core/management/commands/migrate.py,试图找出 django 如何确定其迁移应用程序的顺序。

在第 264 行添加 pdb.set_trace() 语句 (https://github.com/django/django/blob/1.8.3/django/core/management/commands/migrate.py#L264) 并查看 app_labels 包含的内容,我得到:

set(['djangosaml2', 'django_ace', 'recurly', 'staticfiles', 'distributedlock', 'app_overrides', 'messages', 'django_otp', 'kombu_transport_django', 'otp_totp', 'compressor', 'otp_static', 'humanize', 'ajax_select', 'django_extensions', 'import_export', 'raven_compat', 'crispy_forms', 'emoji'])

这是我在决定寻求帮助之前所得到的。有谁知道 Django 最终会如何以正确的顺序创建所有项目的应用程序以便不会发生体面冲突?

【问题讨论】:

  • 先尝试./manage.py makemigrations app,然后继续
  • @Paul 你解决了这个问题吗?我面临同样的事情,除了它抱怨不同的关系。

标签: python django postgresql django-models


【解决方案1】:

就我而言,迁移没有运行,因为我使用了unittest.TestCase 而不是django.test.TestCase

解决方案:替换

from unittest import TestCase

from django.test import TestCase

【讨论】:

    【解决方案2】:

    确保您的所有应用程序目录中都有migrations/ 文件夹和__init__.py 文件。如果没有,请创建一个 migrations/ 文件夹并创建 __init__.py 并在文件夹中复制。如果您使用 git,请在 .gitignore 文件中包含 !migrations/__init__.py

    【讨论】:

    • 尝试了其他所有方法。这对我有用。谢谢。
    【解决方案3】:

    当我在 gitlab CI 作业中运行 manage.py test 时,我遇到了类似的问题,我可以通过在我的 base.py 设置文件中创建一个名为 CI 的变量来解决这个问题

    base.py

    """
    Set CI Variable to True when running: "manage.py test"
    """
    CI = True  
    

    在我的settings.py:

    if CI:
        class DisableMigrations(object):
    
            def __contains__(self, item):
                return True
    
            def __getitem__(self, item):
                return None # For Django 1.10+
    
    MIGRATION_MODULES = DisableMigrations()
    

    【讨论】:

      【解决方案4】:
      python manage.py migrate auth
      

      这行得通。

      【讨论】:

        【解决方案5】:

        我遇到了同样的错误,因为我的 django 应用程序之一没有 migrations 目录。尝试仔细查看INSTALLED_APPS 中存在的所有应用文件夹。

        【讨论】:

          【解决方案6】:

          遇到了同样的问题,由于它发生在 ./manage.py test 上,因此您的迁移可能会中断。
          从 Django 1.7 开始,有一个名为 MIGRATION_MODULES 的新设置,您可以在其中配置应用的迁移模块。
          在 settings.py(找到 here)中添加以下解决方法会跳过测试迁移,并为我解决了这个问题:

          class DisableMigrations(object):
          
              def __contains__(self, item):
                  return True
          
              def __getitem__(self, item):
                  return "notmigrations"
          
          MIGRATION_MODULES = DisableMigrations()
          

          【讨论】:

          • 在 settings.py 文件中添加这些行后,它返回以下错误 - ModuleNotFoundError: No module named 'notmigrations'
          【解决方案7】:

          这应该通过运行来解决:

          python manage.py migrate auth
          python manage.py migrate app
          python manage.py migrate
          

          【讨论】:

            【解决方案8】:

            您没有提供任何代码,因此很难理解您的模型关系。但是我能猜到你已经将 ForeignKey 模型作为实例传递了吗?尝试将其作为字符串提供

            class MyModel(models.Model):
                fk_field = models.ForeignKey('path.to.other.model')    # same as from path.models import model
            

            这通常会奏效。希望它也适合你!

            【讨论】:

              猜你喜欢
              • 2021-03-30
              • 1970-01-01
              • 2021-03-17
              • 2015-10-09
              • 2018-05-11
              • 2014-10-25
              • 2019-03-15
              • 2018-03-23
              • 2021-05-24
              相关资源
              最近更新 更多