具有默认值的外键上的 Django 1.7 迁移错误

Posted

技术标签:

【中文标题】具有默认值的外键上的 Django 1.7 迁移错误【英文标题】:Django 1.7 Migration error on foreignkey with default value 【发布时间】:2014-11-19 22:56:07 【问题描述】:

我在测试我的应用程序时遇到问题,包括在具有默认值的 ForeignKey 模型字段上迁移(参见下面的示例,模型 RuleSet 中的字段 mode)。

我不知道这是 Django 1.7 测试迁移中的错误还是我做错了什么

#models.py:

RULE_SET_MODE__ACTIVE = "Active"

def default_mode():
    return RuleSetMode.objects.get(name=RULE_SET_MODE__ACTIVE)

class RuleSetMode(models.Model):
    name = models.CharField(max_length=30)
    description = models.CharField(max_length=255)

class RuleSet(models.Model):
    name = models.CharField(max_length=30, unique=True)
    description = models.CharField(max_length=255)
    mode = models.ForeignKey(RuleSetMode, default=default_mode)

到目前为止,我尝试了以下迁移步骤:

    使用默认值(函数)创建了初始迁移 创建了一个没有默认值的初始迁移,并通过设置默认值创建了第二个迁移更改字段

它们都不适合我。所以你可以看到问题与迁移字段本身无关。这只是与应用程序存在迁移这一事实有关。

(覆盖保存方法将是一种解决方案,或者在使用此解决方案的测试期间禁用迁移:Disable migrations when running unit tests in Django 1.7,但我更喜欢设置默认属性)

#migrations file (altering the existing field):

# -*- coding: utf-8 -*-
from __future__ import unicode_literals

from django.db import models, migrations
import myapp.models


class Migration(migrations.Migration):

    dependencies = [
        ('myapp', '0001_initial'),
    ]

    operations = [
        migrations.AlterField(
            model_name='ruleset',
            name='mode',
            field=models.ForeignKey(default=myapp.models.default_mode, to='myapp.RuleSetMode'),
        ),
    ]

执行的输出:python manage.py test myapp:

Creating test database for alias 'default'...
Traceback (most recent call last):
File "manage.py", line 16, in <module>
execute_from_command_line(sys.argv)
File "/home/cgossy/venvs/django-1.7/local/lib/python2.7/site-packages/Django-1.7-py2.7.egg/django/core/management/__init__.py", line 385, in execute_from_command_line
utility.execute()
File "/home/cgossy/venvs/django-1.7/local/lib/python2.7/site-packages/Django-1.7-py2.7.egg/django/core/management/__init__.py", line 377, in execute
self.fetch_command(subcommand).run_from_argv(self.argv)
File "/home/cgossy/venvs/django-1.7/local/lib/python2.7/site-packages/Django-1.7-py2.7.egg/django/core/management/commands/test.py", line 50, in run_from_argv
super(Command, self).run_from_argv(argv)
File "/home/cgossy/venvs/django-1.7/local/lib/python2.7/site-packages/Django-1.7-py2.7.egg/django/core/management/base.py", line 288, in run_from_argv
self.execute(*args, **options.__dict__)
File "/home/cgossy/venvs/django-1.7/local/lib/python2.7/site-packages/Django-1.7-py2.7.egg/django/core/management/commands/test.py", line 71, in execute
super(Command, self).execute(*args, **options)
File "/home/cgossy/venvs/django-1.7/local/lib/python2.7/site-packages/Django-1.7-py2.7.egg/django/core/management/base.py", line 338, in execute
output = self.handle(*args, **options)
File "/home/cgossy/venvs/django-1.7/local/lib/python2.7/site-packages/Django-1.7-py2.7.egg/django/core/management/commands/test.py", line 88, in handle
failures = test_runner.run_tests(test_labels)
File "/home/cgossy/venvs/django-1.7/local/lib/python2.7/site-packages/Django-1.7-py2.7.egg/django/test/runner.py", line 147, in run_tests
old_config = self.setup_databases()
File "/home/cgossy/venvs/django-1.7/local/lib/python2.7/site-packages/Django-1.7-py2.7.egg/django/test/runner.py", line 109, in setup_databases
return setup_databases(self.verbosity, self.interactive, **kwargs)
File "/home/cgossy/venvs/django-1.7/local/lib/python2.7/site-packages/Django-1.7-py2.7.egg/django/test/runner.py", line 299, in setup_databases
serialize=connection.settings_dict.get("TEST_SERIALIZE", True),
File "/home/cgossy/venvs/django-1.7/local/lib/python2.7/site-packages/Django-1.7-py2.7.egg/django/db/backends/creation.py", line 374, in create_test_db
test_flush=True,
File "/home/cgossy/venvs/django-1.7/local/lib/python2.7/site-packages/Django-1.7-py2.7.egg/django/core/management/__init__.py", line 115, in call_command
return klass.execute(*args, **defaults)
File "/home/cgossy/venvs/django-1.7/local/lib/python2.7/site-packages/Django-1.7-py2.7.egg/django/core/management/base.py", line 338, in execute
output = self.handle(*args, **options)
File "/home/cgossy/venvs/django-1.7/local/lib/python2.7/site-packages/Django-1.7-py2.7.egg/django/core/management/commands/migrate.py", line 160, in handle
executor.migrate(targets, plan, fake=options.get("fake", False))
File "/home/cgossy/venvs/django-1.7/local/lib/python2.7/site-packages/Django-1.7-py2.7.egg/django/db/migrations/executor.py", line 63, in migrate
self.apply_migration(migration, fake=fake)
File "/home/cgossy/venvs/django-1.7/local/lib/python2.7/site-packages/Django-1.7-py2.7.egg/django/db/migrations/executor.py", line 97, in apply_migration
migration.apply(project_state, schema_editor)
File "/home/cgossy/venvs/django-1.7/local/lib/python2.7/site-packages/Django-1.7-py2.7.egg/django/db/migrations/migration.py", line 107, in apply
operation.database_forwards(self.app_label, schema_editor, project_state, new_state)
File "/home/cgossy/venvs/django-1.7/local/lib/python2.7/site-packages/Django-1.7-py2.7.egg/django/db/migrations/operations/fields.py", line 131, in database_forwards
schema_editor.alter_field(from_model, from_field, to_field)
File "/home/cgossy/venvs/django-1.7/local/lib/python2.7/site-packages/Django-1.7-py2.7.egg/django/db/backends/schema.py", line 509, in alter_field
self._alter_field(model, old_field, new_field, old_type, new_type, old_db_params, new_db_params, strict)
File "/home/cgossy/venvs/django-1.7/local/lib/python2.7/site-packages/Django-1.7-py2.7.egg/django/db/backends/sqlite3/schema.py", line 183, in _alter_field
self._remake_table(model, alter_fields=[(old_field, new_field)])
File "/home/cgossy/venvs/django-1.7/local/lib/python2.7/site-packages/Django-1.7-py2.7.egg/django/db/backends/sqlite3/schema.py", line 121, in _remake_table
self.create_model(temp_model)
File "/home/cgossy/venvs/django-1.7/local/lib/python2.7/site-packages/Django-1.7-py2.7.egg/django/db/backends/schema.py", line 208, in create_model
definition, extra_params = self.column_sql(model, field)
File "/home/cgossy/venvs/django-1.7/local/lib/python2.7/site-packages/Django-1.7-py2.7.egg/django/db/backends/schema.py", line 120, in column_sql
default_value = self.effective_default(field)
File "/home/cgossy/venvs/django-1.7/local/lib/python2.7/site-packages/Django-1.7-py2.7.egg/django/db/backends/schema.py", line 170, in effective_default
default = field.get_default()
File "/home/cgossy/venvs/django-1.7/local/lib/python2.7/site-packages/Django-1.7-py2.7.egg/django/db/models/fields/related.py", line 1711, in get_default
field_default = super(ForeignKey, self).get_default()
File "/home/cgossy/venvs/django-1.7/local/lib/python2.7/site-packages/Django-1.7-py2.7.egg/django/db/models/fields/__init__.py", line 719, in get_default
return self.default()
File "/usr/local/lib/python2.7/dev-packages/kiola/kiola_alfred/models.py", line 33, in default_mode
return RuleSetMode.objects.get(name=RULE_SET_MODE__ACTIVE)
File "/home/cgossy/venvs/django-1.7/local/lib/python2.7/site-packages/Django-1.7-py2.7.egg/django/db/models/manager.py", line 92, in manager_method
return getattr(self.get_queryset(), name)(*args, **kwargs)
File "/home/cgossy/venvs/django-1.7/local/lib/python2.7/site-packages/Django-1.7-py2.7.egg/django/db/models/query.py", line 357, in get
self.model._meta.object_name)
myapp.models.DoesNotExist: RuleSetMode matching query does not exist.

欢迎提出任何意见

【问题讨论】:

【参考方案1】:

我找到了解决问题的方法。

问题在于,在应用迁移时,数据库当然是空的。自从

migrations.AlterField(
        model_name='ruleset',
        name='mode',
        field=models.ForeignKey(default=myapp.models.default_mode, to='myapp.RuleSetMode'),
    ),

用途

models.ForeignKey(default=myapp.models.default_mode, to='myapp.RuleSetMode')

执行用于设置默认值的函数。但是数据库中没有任何价值。

现在我在初始迁移和添加默认值的迁移之间添加了数据迁移。

看起来像这样:

# -*- coding: utf-8 -*-
from __future__ import unicode_literals

from django.db import models, migrations


def set_default_values(apps, schema_editor):
    # We can't import the Person model directly as it may be a newer
    # version than this migration expects. We use the historical version.
    import myapp.const as const
    RuleSetMode = apps.get_model("myapp", "RuleSetMode")
    RuleSetMode.objects.get_or_create(name=const.RULE_SET_MODE__ACTIVE)


class Migration(migrations.Migration):

    dependencies = [
        ('myapp', '0001_initial'),
    ]

    operations = [
        migrations.RunPython(set_default_values),
    ]

并在添加默认值的迁移中将依赖列表更改为:

dependencies = [
    ('myapp', '0002_auto_20140925_1458'),
]

【讨论】:

以上是关于具有默认值的外键上的 Django 1.7 迁移错误的主要内容,如果未能解决你的问题,请参考以下文章

Django 1.9 在迁移中删除外键

使用 django-import-export 在 django 迁移中的外键

Django的外键创建

带有查找字段的嵌套模型外键上的 Django JOIN

我需要在 Oracle 的外键上创建索引吗?

MySQL 性能:两个表在公共外键上的连接:仍然“使用 where”