使用fixture或脚本预填数据库? [英] Prepopulate database with fixtures or with script?

查看:207
本文介绍了使用fixture或脚本预填数据库?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我不是一个专家,但我认为是一个好主意,使用类来定义选择和预填充数据库与这个选择。

I'm not an expert but I think is a good idea using Class to define choices and to prepopulate the database with this choices. I think that make easier to change choices, etc

所以在我的 models.py 我有:

class City(models.Model):
    name = models.CharField(max_length=32)
    distance = models.SmallIntegerField(blank=True, null=True)
    #etc

class OtherClass(models.Model):
    name = models.CharField(max_length=32)
    #etc

class UserProfile(models.Model):
    name = models.CharField(max_length=32)
    city = models.ForeignKey(City)
    otherfield = models.ForeignKey(OtherClass)
    #etc

UserProfile是用户编译的内容,OtherClass是程序员放置选项的地方。

UserProfile is what the users compile, City, OtherClass is where the programmer put the options.

迁移后,我必须创建一些City和OtherClass对象:他们将是选项固定)。

After the migration I have to create some City and OtherClass objects: they will be the options (and yes they have to be fixed).

我只是想了解一下灯具。直到现在我使用脚本

I Just find out about the fixtures. Until now I was using a script:

import os
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'sitopossedimenti.settings')

import django
django.setup()

from core.models import *

def populate():
    namecity1 = add_source('city1', None)
    namecity2 = add_source('city2', None)
    @etc

    nameotherclass1 = add_otherclass('name1', #etc)

    #etc some thousands more

def add_source(name, distance):
    s = model.Source.objects.get_or_create(name=name, distance=distance)[0]
    s.save()
    return s

def add_otherclass:
    #etc

if __name__ == '__main__':
    print ("Starting myapp population script...")
    populate()

现在脚本工作了(大约),我恐怕改变...但你觉得怎么样?灯具更好吗?为什么?有区别吗?

For now the script works (about) and I'm afraid to change... but what do you think? Are the fixture better? Why? There're differences?

推荐答案

俗话说,如果它的工作不解决它。

As the saying goes, if it works don't fix it. Fixtures is the more usual method but no harm in using your own.

如果您想要一种完全自动化的方式来实现结果,请考虑 migration.RunPython 。链接的文档包含一个完整的示例,显示正在加载的数据。显然,这将发生在 ./ manage.py migrate ,而不需要额外的步骤。

If you want a fully automated way of achieving the result, consider migration.RunPython. The linked document contains a full example which shows data being loaded. Obviously this will happen with ./manage.py migrate without the need of an additional step.

这篇关于使用fixture或脚本预填数据库?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆