【问题标题】:Order of Django Data MigrationsDjango 数据迁移的顺序
【发布时间】:2017-10-31 12:49:32
【问题描述】:

我在我的应用程序中使用站点应用程序 (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'

【问题讨论】:

  • python manage.py 站点。在为您的应用启动命令之后。

标签: python django django-migrations


【解决方案1】:

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

更新

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

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

相关文档文章here.

【讨论】:

  • 好的,虽然我真的想要一种方法来强制站点应用程序在访问模型之前迁移,这样我的最终用户就可以像往常一样运行python manage.py migrate - 一切正常 - 开始时我的库中的一个新应用程序。
  • 更新了我的答案。
  • 好的,更新后的解决方案有效 - 对我来说有一个小改动:站点迁移运行后站点不存在,您只需使用 current= Site.objects.create(domain=...',name=...) 而不是 current= Site.objects.get_current() 创建站点.
猜你喜欢
  • 2023-04-06
  • 2018-07-14
  • 2018-03-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-01-12
  • 1970-01-01
相关资源
最近更新 更多