Django 1.8 在引用 django_content_type 之前创建表然后失败

标签 django postgresql django-contenttypes

我正在尝试创建 ContentType 引用 ( https://docs.djangoproject.com/en/1.8/ref/contrib/contenttypes/#generic-relations )

myobj/models.py:

from django.db import models
from django.contrib.contenttypes.fields import GenericForeignKey
from django.contrib.contenttypes.models import ContentType


class TaggedItem(models.Model):
    tag = models.SlugField()
    content_type = models.ForeignKey(ContentType)
    object_id = models.PositiveIntegerField()
    content_object = GenericForeignKey('content_type', 'object_id')

当我开始测试(manage.py test -v3)时,我得到回溯:

Traceback (most recent call last):
  File "manage.py", line 10, in <module>
    execute_from_command_line(sys.argv)
  File "/home/alexander/.local/lib/python2.7/site-packages/django/core/management/__init__.py", line 338, in execute_from_command_line
    utility.execute()
  File "/home/alexander/.local/lib/python2.7/site-packages/django/core/management/__init__.py", line 330, in execute
    self.fetch_command(subcommand).run_from_argv(self.argv)
  File "/home/alexander/.local/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 "/home/alexander/.local/lib/python2.7/site-packages/django/core/management/base.py", line 390, in run_from_argv
    self.execute(*args, **cmd_options)
  File "/home/alexander/.local/lib/python2.7/site-packages/django/core/management/commands/test.py", line 74, in execute
    super(Command, self).execute(*args, **options)
  File "/home/alexander/.local/lib/python2.7/site-packages/django/core/management/base.py", line 441, in execute
    output = self.handle(*args, **options)
  File "/home/alexander/.local/lib/python2.7/site-packages/django/core/management/commands/test.py", line 90, in handle
    failures = test_runner.run_tests(test_labels)
  File "/home/alexander/.local/lib/python2.7/site-packages/django/test/runner.py", line 210, in run_tests
    old_config = self.setup_databases()
  File "/home/alexander/.local/lib/python2.7/site-packages/django/test/runner.py", line 166, in setup_databases
    **kwargs
  File "/home/alexander/.local/lib/python2.7/site-packages/django/test/runner.py", line 370, in setup_databases
    serialize=connection.settings_dict.get("TEST", {}).get("SERIALIZE", True),
  File "/home/alexander/.local/lib/python2.7/site-packages/django/db/backends/base/creation.py", line 368, in create_test_db
    test_flush=True,
  File "/home/alexander/.local/lib/python2.7/site-packages/django/core/management/__init__.py", line 120, in call_command
    return command.execute(*args, **defaults)
  File "/home/alexander/.local/lib/python2.7/site-packages/django/core/management/base.py", line 441, in execute
    output = self.handle(*args, **options)
  File "/home/alexander/.local/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 "/home/alexander/.local/lib/python2.7/site-packages/django/core/management/commands/migrate.py", line 317, in sync_apps
    cursor.execute(statement)
  File "/home/alexander/.local/lib/python2.7/site-packages/django/db/backends/utils.py", line 64, in execute
    return self.cursor.execute(sql, params)
  File "/home/alexander/.local/lib/python2.7/site-packages/django/db/utils.py", line 97, in __exit__
    six.reraise(dj_exc_type, dj_exc_value, traceback)
  File "/home/alexander/.local/lib/python2.7/site-packages/django/db/backends/utils.py", line 62, in execute
    return self.cursor.execute(sql)
django.db.utils.ProgrammingError: ERROR: reference "django_content_type" does not exist

我的设置.py:

...
INSTALLED_APPS = (
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.staticfiles',
    'myobj',
)
...
DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.postgresql_psycopg2', # Add 'postgresql_psycopg2', 'mysql', 'sqlite3' or 'oracle'.
        'NAME': 'mydb',                      # Or path to database file if using sqlite3.
        'USER': 'user',                      # Not used with sqlite3.
        'PASSWORD': 'pass',                  # Not used with sqlite3.
        'HOST': '127.0.0.1',                 # Set to empty string for localhost. Not used with sqlite3.
        'PORT': '5432',                      # Set to empty string for default. Not used with sqlite3.
        'TEST_NAME': "testdb_%i_%i" % (random.randrange(1,1000000),random.randrange(1,10000000)),
    }
}
...

Postgresql 日志:

ALTER TABLE "myobj_taggeditem" ADD CONSTRAINT "myob_content_type_id_708726b4e928b107_fk_django_content_type_id" FOREIGN KEY ("content_type_id") REFERENCES "django_content_type" ("id") DEFERRABLE INITIALLY DEFERRED
ERROR:  reference "django_content_type" does not exist

如果我将数据库引擎更改为 SQLite,一切都可以。 它出什么问题了? 我正在使用 django 1.8

最佳答案

您必须为您的 myobj 应用创建迁移。未迁移的应用程序不能依赖于已迁移的应用程序。

只需运行python manage.py makemigrations myobj,它将为您的应用创建初始迁移。

它在 SQLite3 上“工作”的原因是 Django 在 SQLite 中不强制执行外键约束。

关于Django 1.8 在引用 django_content_type 之前创建表然后失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29608659/

相关文章:

python - Paypal 整合错误

python - 我如何有两个字段可供选择?

mysql - 名称-值对模型 对于仅配置数据

Node.js、Express 和 Postgres 设计

python - Django ReverseSingleRelatedObjectDescriptor.__set__ ValueError

python - 创建django权限,报错: ContentType matching query does not exist

python - 检查文本是否以空格开头

python - 返回浮点(值)值错误: could not convert string to float in Django models

sql - 如何在一个命令中将一个表中的自动递增 id 插入到另一个表中(使用返回)?

python - 如何从列表中生成组合 Q 对象?