做项目时需要导入一些测试数据,我们当然可以在shell中一条条加,但数据一多,这也太费劲了。
其实可以单独的使用Django中Model进行操作,将测试数据提前写入txt或py文件中,再在处理脚本中用Model的方法循环创建。
import_data.py
import os
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "MxShop.settings")
import django
django.setup()
from goods.models import GoodsCategory
from db_tools.data.category_data import row_data
for lev1_cat in row_data:
lev1_intance = GoodsCategory()
lev1_intance.code = lev1_cat["code"]
lev1_intance.name = lev1_cat["name"]
lev1_intance.category_type = 1
lev1_intance.save()
for lev2_cat in lev1_cat["sub_categorys"]:
lev2_intance = GoodsCategory()
lev2_intance.code = lev2_cat["code"]
lev2_intance.name = lev2_cat["name"]
lev2_intance.category_type = 2
lev2_intance.parent_category = lev1_intance
lev2_intance.save()
for lev3_cat in lev2_cat["sub_categorys"]:
lev3_intance = GoodsCategory()
lev3_intance.code = lev3_cat["code"]
lev3_intance.name = lev3_cat["name"]
lev3_intance.category_type = 3
lev3_intance.parent_category = lev2_intance
lev3_intance.save()
category_data.py
row_data = [
{
'sub_categorys': [
{
'sub_categorys': [
{
'code': 'yr',
'name': '羊肉'
},
{
'code': 'ql',
'name': '禽类'
},
{
'code': 'zr',
'name': '猪肉'
},
{
'code': 'nr',
'name': '牛肉'
}
],
'code': 'jprl',
'name': '精品肉类'
}],
'code': 'sxsp',
'name': '生鲜食品',
}
]
import django
django.setup()
对Django初始化前需先设置环境变量
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "MxShop.settings")
否则报错
django.core.exceptions.ImproperlyConfigured: Requested setting LOGGING_CONFIG, but settings are not configured. You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings.
参考:https://code.ziqiangxuetang.com/django/django-import-data.html