栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

使用Django 1.7加载初始数据和数据迁移

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

使用Django 1.7加载初始数据和数据迁移

假设你有一个夹具文件 /fixtures/initial_data.json

创建空迁移:

在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从将加载器具的fixtures目录自动:

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>


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/404880.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号