South 只需修补 syncdb 以跳过具有迁移的模型的夹具加载,并在运行应用的最终迁移后实际加载它们。
确保您的 initial_data 文件位于正确的位置
加载initial_data并不需要你实际做某事,而是将fixtures放在the correct place as explained in Django's documentation中。
引用文档:
默认情况下,Django 会在每个应用程序内的 fixtures 目录中查找
固定装置。您可以将 FIXTURE_DIRS 设置设置为附加列表
Django 应该查看的目录。
这意味着如果您有一个名为“myapp”的应用程序,您将在其中创建一个“fixtures”目录并将 json 放在那里,例如:myproject/myapp/fixtures。
Django 1.7 及更新版本
Django 1.7 introduced built-in migrations。它们有一个类似于 South 的界面;用于创建迁移makemigrations、运行它们migrate 等的管理命令。
但是,initial_data 装置不再在 syncdb 运行时自动加载;除非它是现有的应用程序,并且没有迁移。这是mentioned in the release notes。
文档现在建议创建一个datamigration 来处理夹具加载。幸运的是,这很容易做到,这就是我通常的做法:
$ python manage.py makemigrations --empty myapp
如果您只有初始迁移,您最终会得到这些文件(请注意,为了清楚起见,我将迁移 0002 重命名):
myapp/
├── __init__.py
├── fixtures
│ └── my_initial_data.json
└── migrations
├── 0001_initial.py
├── 0002_load_fixture.py
└── __init__.py
2。更新0002_load_fixture.py的代码运行loaddata
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import migrations
from django.core.management import call_command
def load_my_initial_data(apps, schema_editor):
call_command("loaddata", "my_initial_data.json")
class Migration(migrations.Migration):
dependencies = [
('myapp', '0001_initial'),
]
operations = [
migrations.RunPython(load_my_initial_data),
]