gpt4 book ai didi

python - 使用固定装置或脚本预填充数据库?

转载 作者:搜寻专家 更新时间:2023-10-30 20:25:25 24 4
gpt4 key购买 nike

我不是专家,但我认为使用类来定义选择并使用这些选择预填充数据库是个好主意。我认为这样更容易改变选择等

所以在我的 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是用户编译的,CityOtherClass是程序员放选项的地方。

迁移后,我必须创建一些 CityOtherClass 对象:它们将是选项(是的,它们必须被修复)。

我刚刚了解了 fixtures .到目前为止,我一直在使用脚本:

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()

目前脚本可以(大约)工作,我不敢更改...但是您怎么看?固定装置更好吗?为什么?有区别吗?

最佳答案

俗话说,能行不修。固定装置是更常用的方法,但使用您自己的固定装置也无妨。如果您正在编写一个新的测试用例,您可能想要使用固定装置,但如果我是你,我会顺其自然。

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

使用 migrations.RunPython 的优势在于,如果您要与同事共享您的应用程序或安装在不同的服务器上,所需的数据将自动加载到生产服务器中,并且测试也可以完全访问它在测试数据库中。

关于python - 使用固定装置或脚本预填充数据库?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37076858/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com