models模型中有文章主表DetailInfo、文章分类表Types、文章资源表ResourcesLink,有一对多和多对多的关系。

1、models.py:

`# 文章分类
class Types(models.Model):
    name = models.CharField(max_length=10,verbose_name="类型名称")

#文章信息表
class DetailInfo(models.Model):
    title = models.CharField(max_length=200,blank=False,verbose_name="文章名称")
    types = models.ManyToManyField(Types,verbose_name="文章类型")
    context = models.TextField(max_length=1024,verbose_name="文章内容")
    ...
 # 文章资源表
class ResourcesLink(models.Model):
    detailinfo = models.ForeignKey(DetailInfo, on_delete=models.CASCADE,verbose_name="文章信息")
    title =  models.CharField(max_length=200,verbose_name="资源名称")
    link = models.CharField(max_length=500,verbose_name="资源链接")
    ...`

2、json数据格式

[
  {
    
    "标题": "小武",   
    "内容": "测试",
    "类型":["情感","文学","散文"]
    "文章资源":[{
                "title":"小武.1998.HD.1080p.x264.aac.Mandarine .CHS.mkv ",
                "links":"https://www.xxx1.com"
              },
              {
                "title":"小武.1998.HD.1080p.x264.aac.Mandarin.CHS.mp4",
                "links":"https://www.xxx2.com"
                }]
  },
 {
 ...
 }   
]

3.实现批量插入数据

from (自己项目名称).wsgi import *
from (app名称).models import Types,DetailInfo,MagnetLink
import json

def insertDB():

    with open('E:workspacexxxxx.json', 'r', encoding='utf8') as f:
        data = json.load(f)
        for list in data:

            #先写入分类(多对多关系)
            for t in list['类型']:
                c = Types.objects.get_or_create(name=t)[0]
                # 然后插入文章
                article = DetailInfo.objects.get_or_create(title=list['标题'],
                    context=list['内容'])[0]
                # 获取文章id
                article_id = article.id
                
                for m in list['文章资源']:
                    print(m)
                    # 根据文章id将数据插入到文章资源表中(一对多)                   
                    ResourcesLink.objects.get_or_create(detailinfo_id=article_id,title=m['title'],link=m['links'])[0]
                 
                 #最后将分类添加到文章中
                article.types.add(c)

xiaomayi2012
300 声望7 粉丝