use*_*546 3 python django django-migrations
我想要像Users and Options.
对于旧的 django 来说,fixtures 是非常简单的方法,但现在 django 说要以我不完全理解的迁移方式来做。
现在我的迁移文件夹中已经有 10 个迁移。我很困惑我在哪里保存我的初始数据迁移文件。
如果我喜欢0011_initial_data并把它放在其他迁移中,那么它会在长长的迁移列表中丢失,并且新用户不容易注意到那是什么。而且如果有人压制迁移,那么没有人会知道那里是否有一些数据。
我想将它放在某个名为 data migration 的文件夹中。我怎样才能做到这一点
这是他们网站上的示例代码。但是我应该把它放在哪里以免混淆
# -*- 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),
]
Run Code Online (Sandbox Code Playgroud)
就像@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),
]
Run Code Online (Sandbox Code Playgroud)
Django 会像往常一样查找夹具文件,并在您迁移数据库时加载您的数据。