假设你有一个夹具文件
创建空迁移:
在Django 1.7中:
python manage.py makemigrations --empty <yourapp>
在Django 1.8+中,你可以提供一个名称:
python manage.py makemigrations --empty <yourapp> --name load_intial_data
编辑你的迁移文件
<yourapp>/migrations/0002_auto_xxx.py
2.1。自定义实现,受Django’
loaddata(初始答案)启发:
import osfrom sys import pathfrom django.core import serializersfixture_dir = os.path.abspath(os.path.join(os.path.dirname(__file__), '../fixtures'))fixture_filename = 'initial_data.json'def load_fixture(apps, schema_editor): fixture_file = os.path.join(fixture_dir, fixture_filename) fixture = open(fixture_file, 'rb') objects = serializers.deserialize('json', fixture, ignorenonexistent=True) for obj in objects: obj.save() fixture.close()def unload_fixture(apps, schema_editor): "Brutally deleting all entries for this model..." MyModel = apps.get_model("yourapp", "ModelName") MyModel.objects.all().delete()class Migration(migrations.Migration): dependencies = [ ('yourapp', '0001_initial'), ] operations = [ migrations.RunPython(load_fixture, reverse_pre=unload_fixture), ]2.2。一个简单的解决方案load_fixture(根据@juliocesar的建议):
from django.core.management import call_commandfixture_dir = os.path.abspath(os.path.join(os.path.dirname(__file__), '../fixtures'))fixture_filename = 'initial_data.json'def load_fixture(apps, schema_editor): fixture_file = os.path.join(fixture_dir, fixture_filename) call_command('loaddata', fixture_file) 如果要使用自定义目录,则很有用。
2.3。最简单的:调用loaddata与app_label从将加载器具
from django.core.management import call_commandfixture = 'initial_data'def load_fixture(apps, schema_editor): call_command('loaddata', fixture, app_label='yourapp') 如果你未指定
app_label,loaddata将尝试
fixture从所有应用程序的夹具目录(你可能不希望这样做)中加载文件名。
运行
python manage.py migrate <yourapp>



