2016-09-28 50 views
5

我希望我的应用程序具有默认数据,例如用户类型。什么是迁移后管理默认数据的最有效方式。Django在迁移后插入默认数据

它需要处理的情况下,例如我添加一个新的表后,它添加了它的默认数据。

回答

1

我想你正在寻找的是fixtureshttps://docs.djangoproject.com/en/1.10/howto/initial-data/

从文档

它有时有用的预填充硬编码的数据当你第一次建立一个应用程序的数据库。您可以通过灯具提供初始数据。

也阅读了本https://code.djangoproject.com/wiki/Fixtures

+0

该文档抵触这样的回答: “如果你想自动加载初始数据的应用程序,不使用固定装置相反,创建与RunPython或RunSQL操作您的应用程序迁移。” – Dennis

+0

@Dennis OP问道:“迁移后管理默认数据的最有效方法是什么?”即使有关于迁移的答案,他选择我的答案作为他的问题的正确答案。 –

+0

@丹尼斯您从文档中使用的引用也是关于应用程序而不是项目。 –

10

您需要创建一个空的迁移文件,做你的东西,在操作区块,如文档解释。

Data Migrations

以及改变数据库模式,您也可以使用迁移,如果你想使用的模式来改变数据库本身的数据,并结合。

现在,所有你需要做的就是创建一个新的功能,并RunPython使用它

文档解释了这个用一个例子来说明,如何与您的模型进行通信。

从文档

要创建一个空的迁移文件,

python manage.py makemigrations --empty yourappname 

这是如何更新新增加的字段的例子。

# -*- coding: utf-8 -*- 
from __future__ import unicode_literals 

from django.db import migrations, models 

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): 
    initial = True 

    dependencies = [ 
     ('yourappname', '0001_initial'), 
    ] 

    operations = [ 
     migrations.RunPython(combine_names), 
    ] 
+2

这应该是被接受的答案。 – shuboy2014