Django 多对多的保存

Models 模型如下:

from django.db import models

# Create your models here.

class Category(models.Model):
    cate_name = models.CharField(max_length=30)
    cate_desc = models.CharField(max_length=100)
    cate_slug = models.CharField(max_length=30)

    def __str__(self):
        return self.cate_name

    class Meta:
        db_table="movie_cate"


class Tag(models.Model):
    tag_name = models.CharField(max_length=30)
    tag_desc = models.CharField(max_length=100)
    tag_slug = models.CharField(max_length=30)

    def __str__(self):
        return self.tag_name

    class Meta:
        db_table="movie_tag"

class Director(models.Model):
    name = models.CharField(max_length=30)
    desc = models.TextField(blank=True)

    def __str__(self):
        return self.name

    class Meta:
        db_table="director"

class Actor(models.Model):
    name = models.CharField(max_length=30)
    desc = models.TextField(blank=True)

    def __str__(self):
        return self.name

    class Meta:
        db_table="actor"

class Dl_links(models.Model):
    links = models.CharField(max_length=200)
    links_name = models.CharField(max_length=30)

    def __str__(self):
        return self.links_name

    class Meta:
        db_table="dl_links"

class Movie(models.Model):
    title = models.CharField(max_length=50)
    category = models.ForeignKey(Category)
    directors = models.ManyToManyField(Director)
    actors = models.ManyToManyField(Actor)
    poster = models.CharField(max_length=100)
    tags = models.ManyToManyField(Tag)
    other_name = models.CharField(max_length=100,default='')
    dl_links = models.ForeignKey(Dl_links,null=True,default='')
    score = models.IntegerField()


    def __str__(self):
        return self.title

    class Meta:
        db_table="movie"
Django 多对多的保存-Python 技术分享 Java技术分享 Python 爬虫技术_微信公众号:zeropython—昊天博客

多对多的保存

首先查询出 多对多需要用的

"""
    category = models.ForeignKey(Category)
    directors = models.ManyToManyField(Director)
    actors = models.ManyToManyField(Actor)
    tags = models.ManyToManyField(Tag)
    dl_links = models.ForeignKey(Dl_links,null=True,default='')
"""

In [1]: from movie.models import *

In [2]: c1 = Category.objects.get(pk=1)

In [3]: c1
Out[3]: <Category: 分类0>

In [4]: d1 = Director.objects.get(pk=1)

In [5]: d1
Out[5]: <Director: 0导演>

In [6]: d2 = Director.objects.get(pk=2)

In [7]: t1 = Tag.objects.get(pk=1)

In [8]: t2 = Tag.objects.get(pk=2)

In [9]: dl1 = Dl_links.objects.get(pk=1)

# 保存多对一的类型
In [19]: mv= Movie.objects.create(title='海王',category=c1,poster="ddd",other_na
    ...: me='d',dl_links=dl1,score=10)
# 保存与之关联的多对多
In [21]: mv.directors.add(d1,d2)

In [22]: mv.tags.add(t1,t2)

In [23]: mv.actors.add(a1,a2)
In [24]: mv
Out[24]: <Movie: 海王>    
Django 多对多的保存-Python 技术分享 Java技术分享 Python 爬虫技术_微信公众号:zeropython—昊天博客
HTTPX 基础教程-新乡seo|网站优化,网站建设_微信公众号:zeropython—昊天博客