Django 数据迁移顺序

Order of Django Data Migrations

我在我的应用程序中使用站点应用程序 (django.contrib.sites)。我创建了一个数据迁移,它在创建数据库时设置当前站点的值,但是我的数据迁移是在安装站点应用程序之前执行的。如何在 sites 次迁移后强制执行数据迁移。

此项目旨在成为用于其他项目的种子,我经常删除数据库并重新开始,因此初始 makemigrations/migrate 命令开箱即用非常重要。

我的迁移文件存在于主应用程序文件夹中:

project folder
..+app
....+migrations
......-0001_initial.py

迁移文件的内容如下:

from __future__ import unicode_literals

from django.db import migrations

def set_development_site(apps, schema_editor):
    Site = apps.get_model('sites', 'Site')
    current= Site.objects.get_current()
    current.domain = "localhost:8000"
    current.name = "Django-Angular-Webpack-Starter"
    current.save()

class Migration(migrations.Migration):

    dependencies = [
    ]

    operations = [
        migrations.RunPython(set_development_site),
    ]

以及 python manage.py migrate 命令的输出:

Operations to perform:
  Apply all migrations: admin, app, auth, authentication, authtoken, contenttypes, sessions, sites
Running migrations:
  Applying contenttypes.0001_initial... OK
  Applying contenttypes.0002_remove_content_type_name... OK
  Applying auth.0001_initial... OK
  Applying authentication.0001_initial... OK
  Applying admin.0001_initial... OK
  Applying admin.0002_logentry_remove_auto_add... OK
  Applying app.0001_initial...Traceback (most recent call last):
  File "/home/user/devel/django-angular-webpack-starter/venv/lib/python3.5/site-packages/django/apps/registry.py", line 149, in get_app_config
    return self.app_configs[app_label]
KeyError: 'sites'

默认情况下不启用(迁移)站点框架。这就是为什么您不能在站点迁移之前引用 Site 模型。您必须先 enable 并迁移它。你想做:manage.py migrate sitesmanage.py migrate.

更新

如果您只想使用 manage.py migrate,请尝试将 sites 添加为迁移文件的依赖项:

dependencies = [
    ('sites', '0001_initial'),
    ...
]

相关文档文章here.