背景说明:
在Django 建立好 models 表之后,使用 python shell 直接逐条导入数据效果太慢
代码架构
Json 数据表结构举例
导入 category 的数据说明(注意这只是包含三级分类的部分数据)
row_data = [
{
'sub_categorys': [
{
'sub_categorys': [
{
'code': 'yr',
'name': '羊肉'
},
{
'code': 'ql',
'name': '禽类'
},
{
'code': 'zr',
'name': '猪肉'
},
{
'code': 'nr',
'name': '牛肉'
}
],
'code': 'jprl',
'name': '精品肉类'
},
导入脚本代码实现 import_category_data.py
# -*- coding: utf-8 -*-
__author__ = 'bobby'
#独立使用django的model
import sys
import os
# 先设置环境
pwd = os.path.dirname(os.path.realpath(__file__))
sys.path.append(pwd+"../")
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()
常见问题
1 )import goods 的时候 找不到 goods ,可以在 import 之前加上 apps. 直接制定好绝对路径
2)在脚本中需要加上 #!/bin/python 不需要
3)在 linux 中执行脚本不用 ./ 使用 python3
4)在使用 os.environ.setdefault 的时候出现 DJANGO_SETTINGS_MODULE No Module Named
在设置路径 sys.path.append 的时候,可以考虑直接插入路径,不要使用 pwd 间接获取路径了
pwd = os.path.dirname(os.path.realpath(file))
sys.path.append(pwd+“…/”) #错误做法
sys.path.append(‘/home/mx/mx_share/mx_shop’) #正确做法
错误:
RuntimeError: Model class apps.goods.models.GoodsCategory doesn't declare an explicit app_label and isn't in an application in INSTALLED_APPS.
解决办法:
1)在 settings.py 的 INSTALLED_APPS 中使用 config 而不是 app 名字进行
2)在第三方脚本中导入 models 使用相对路径,不要使用绝对路径(参考文章)