我如何为 django 1.8 编写初始数据

Posted

技术标签:

【中文标题】我如何为 django 1.8 编写初始数据【英文标题】:How can i write the initial data for django 1.8 【发布时间】:2015-07-21 09:30:14 【问题描述】:

我想获得Users and Options 等表的初始数据。

对于老 django 来说,固定装置是非常简单的方法,但现在 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),
    ]

【问题讨论】:

这里是答案:***.com/a/25981899/548165 @catavaran 我想将该迁移与其他迁移分开。在那个问题中,他们只是将固定装置保存在单独的文件夹中,但迁移仍然与其他文件一起使用 @user3214546 这不可能,Django 不支持单个应用程序的多个迁移文件夹。 【参考方案1】:

就像@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 文件,并且在您迁移数据库时会加载您的数据。

【讨论】:

假设运行此迁移后,我更改了我的夹具文件中的数据,那么会发生什么。相同的迁移将如何再次运行 您可以在数据迁移之前回滚到迁移,然后只需调用 migrate 即可重新应用迁移以及所有以后的迁移。 docs.djangoproject.com/en/1.8/ref/django-admin/…

以上是关于我如何为 django 1.8 编写初始数据的主要内容,如果未能解决你的问题,请参考以下文章

我如何为包含数组数组的对象编写猫鼬模式?

如何为使用两个数据库(mysql和mongo)的django项目编写单元测试

如何为Android Studio编写插件?

如何为 Product* getProductFromID(std::string) 编写方法定义;

如何为 django-rest-framework api 编写单元测试?

如何为mesos和HAProxy进程编写prometheus警报规则。?