Django 2.0使用脚本填充数据库 [英] Django 2.0 Populating Database with a Script
问题描述
我正在尝试使用脚本填充Django数据库,因此不必手动输入数据.到目前为止,我有以下内容:
I'm trying to populate my Django database with a script so I don't have to enter in the data manually. So far I have the following:
from my_app.models import ModelInApp
import django
django.setup()
def add_data(data1, data2):
d, created = ModelInApp.objects.get_or_create(data1=data1, data2=data2)
print("- Data: {0}, Created: {1}".format(str(d), str(created)))
return d
def populate():
# data is a list of lists
for row in data:
data1 = row[0]
data2 = row[1]
add_data(data1, data2)
if __name__ == "__main__":
populate()
data变量是包含我要放入数据库中的数据的列表的列表.问题是,当我运行脚本时,出现django.core.exceptions.AppRegistryNotReady: Apps aren't loaded yet.
错误.我正在使用PostgreSQL作为数据库.
The data variable is a list of lists containing the data I want to put into my database. The problem is, when I run the script, I get a django.core.exceptions.AppRegistryNotReady: Apps aren't loaded yet.
error. I am using PostgreSQL as the database.
我在做什么错了?
推荐答案
解决方案的快速方法是从Django shell(python manage.py shell
)填充数据库.您的没有import django
和django.setup()
的代码应该可以正常工作.快速与肮脏;)
The fast way to work it out is to populate your DB from Django shell (python manage.py shell
). Your code without import django
and django.setup()
should work fine. Fast & dirty ;)
添加数据的超级正确方法是使用数据迁移: https://simpleisbetterthancomplex.com/tutorial/2017/09/26/how-to-create-django-data-migrations.html
The super-proper way to add data is to use data migration: https://simpleisbetterthancomplex.com/tutorial/2017/09/26/how-to-create-django-data-migrations.html
此外,请考虑使用 bulk_create
使事情更有效率(先过滤数据列表,避免重复)
Also, consider using bulk_create
to make things more efficient (filter the data list before to avoid duplicates or so)
这篇关于Django 2.0使用脚本填充数据库的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!