Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
3.7k views
in Technique[技术] by (71.8m points)

请教,django中 如何向带有外键(一对多和多对多)数据库中批量插入数据?

请教,自己采集了一些数据,想批量插入到django中,Models模型代码如下,我想把采集的数据批量插入到 文章信息表DetailInfo中,因为DetailInfo表中涉及到一对多多对多关系,请教我该如何实现批量插入数据?非常感谢~!

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="资源链接")
    ...

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

已自行解决,代码如下:
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"
                }
              ]
  },
 {
 ...
 } 
  
]
from (自己项目名称).wsgi import *
from (app名称).models import Types,DetailInfo,MagnetLink
import json

def insertDB():

    with open('E:\workspace\xxxxx.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)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...