[英]How can i write the initial data for django 1.8
我想拥有像Users and Options
这样的表的初始数据。
对于旧的django来说,固定装置是非常简单的方法,但现在django说要以迁移方式进行,我还不完全了解。
现在我的迁移文件夹中已有10次迁移。 我很困惑我在哪里保留我的初始数据迁移文件。
如果我将它设置为0011_initial_data
并将其放入其他迁移中,那么它将在漫长的迁移列表中丢失,并且新用户不容易注意到它是什么。 如果有人挤压迁移,那么没有人会知道那里是否有一些数据。
我想在一个名为数据迁移的文件夹中将它分开。 我怎样才能做到这一点
这是他们网站的示例代码。 但是我在哪里放置它以免混淆
# -*- coding: utf-8 -*-
from django.db import models, migrations
def combine_names(apps, schema_editor):
# We can't import the Person model directly as it may be a newer
# version than this migration expects. We use the historical version.
Person = apps.get_model("yourappname", "Person")
for person in Person.objects.all():
person.name = "%s %s" % (person.first_name, person.last_name)
person.save()
class Migration(migrations.Migration):
dependencies = [
('yourappname', '0001_initial'),
]
operations = [
migrations.RunPython(combine_names),
]
就像@knbk所说的那样,你无法将迁移带出它的位置。 但是,如果您希望在其他迁移之间进行迁移,但将夹具数据放在单独的文件中,则可以执行以下操作:
from django.core.management import call_command
from django.db import models, migrations
class Migration(migrations.Migration):
def load_data(apps, schema_editor):
call_command("loaddata", "initial_data.json")
dependencies = [
('other_app', '0001_initial'),
]
operations = [
migrations.RunPython(load_data),
]
Django将以与以往一样的方式查找fixture文件,并在迁移数据库时加载数据。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.