当前位置: 首页 > 后端技术 > Python

在django中,使用外键批量向数据库中插入数据(一对多和多对多)

时间:2023-03-25 22:25:07 Python

models模型中有文章主表DetailInfo、文章分类表Types、文章资源表ResourcesLink,它们之间存在一对多和多对多的关系。1.models.py:`#文章分类类Types(models.Model):name=models.CharField(max_length=10,verbose_name="typename")#文章信息表类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="文章内容")...#文章资源表classResourcesLink(models.Model):detailinfo=models.ForeignKey(DetailInfo,on_delete=models.CASCADE,verbose_name="articleinformation")title=models.CharField(max_length=200,verbose_name="resourcename")link=models.CharField(max_length=500,verbose_name="resourcelink")...`2、json数据格式[{"title":"小武","content":"test","type":["情感","文学","散文"]"文章资源":[{"title":"小武.1998.HD.1080p.x264.aac.Mandarine.CHS.mkv","links":"https://www.xxx1.com"},{"title":"Xiaowu.1998.HD.1080p.x264.aac.Mandarin.CHS.mp4","links":"https://www.xxx2.com"}]},{...}]3.实现批量插入数据(自己的项目名称).wsgiimport*from(appname).modelsimportTypes,DetailInfo,MagnetLinkimportjsondefinsertDB():withopen('E:workspacexxxxx.json','r',encoding='utf8')asf:data=json.load(f)forlistindata:#先写分类(多对多关系)fortinlist['type']:c=Types.objects.get_or_create(name=t)[0]#然后插入文章article=DetailInfo.objects.get_or_create(title=list['title'],context=list['content'])[0]#获取文章idarticle_id=article.idforminlist['articleresources']:print(m)#根据文章id向文章资源表插入数据(一对多)ResourcesLink.objects.get_or_create(detailinfo_id=article_id,title=m['title'],link=m['链接'])[0]#最后给文章添加类别article.types.add(c)