代码之家  ›  专栏  ›  技术社区  ›  Maverik Minett

Django数据迁移顺序

  •  0
  • Maverik Minett  · 技术社区  · 8 年前

    我正在使用sites应用程序( 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'
    
    1 回复  |  直到 8 年前
        1
  •  2
  •   Siegmeyer    8 年前

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

    使现代化

    如果您只想使用 管理py迁移 尝试添加 sites 作为迁移文件的依赖项:

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

    相关文件条款 here.