• Django---(五)


    多对多

    表结构的设计

    class Book(models.Model):
        title = models.CharField(max_length=32)
        pub = models.ForeignKey('Publisher', on_delete=models.CASCADE)
    
    
    class Author(models.Model):
        name = models.CharField(max_length=32)
        books = models.ManyToManyField('Book')  # 描述多对多的关系  不生成字段  生成关系表
    

    查询

    all_authors = models.Author.objects.all().order_by('id')
    
    for author in all_authors:
        print(author)
        print(author.name)
        print(author.pk)
        print(author.books)  # 关系管理对象
        print(author.books.all())  # 所关联的所有对象
        print('*' * 32)
    

    新增

    books = request.POST.getlist('books')   # 获取多个元素
    
    # 新建作者
    author_obj = models.Author.objects.create(name=name)
    # 给作者和书籍绑定关系
    author_obj.books.set(books) # 【id,id】
    
    

    创建多对多的表的方法

    1. django通过ManyToManyField自动创建第三张表
    class Book(models.Model):
        title = models.CharField(max_length=32)
        pub = models.ForeignKey('Publisher', on_delete=models.CASCADE)
        # authors = models.ManyToManyField('Author')  # 描述多对多的关系   不生成字段  生成关系表
    
        def __repr__(self):
            return self.title
    
        __str__ = __repr__
    
    class Author(models.Model):
        name = models.CharField(max_length=32)
        books = models.ManyToManyField('Book')  # 描述多对多的关系   不生成字段  生成关系表
    
    1. 自己手动创建
    class Book(models.Model):
        title = models.CharField(max_length=32)
    
    
    class Author(models.Model):
        name = models.CharField(max_length=32)
    
    
    class Book_Author(models.Model):
        book = models.ForeignKey(Book, on_delete=models.CASCADE)
        author = models.ForeignKey(Author, on_delete=models.CASCADE)
        date = models.DateField()
    
    1. 自己创建 + ManyToManyField
    class Book(models.Model):
        title = models.CharField(max_length=32)
    
    
    class Author(models.Model):
        name = models.CharField(max_length=32)
        books = models.ManyToManyField(Book, through='Book_Author')
    
    
    class Book_Author(models.Model):
        book = models.ForeignKey(Book, on_delete=models.CASCADE)
        author = models.ForeignKey(Author, on_delete=models.CASCADE)
        date = models.DateField()
    
  • 相关阅读:
    Day20:Decorator and Metaclass
    Day19:hasattribute;getattribute;seattributet;delattribute
    Day18:polymorphic and reflection
    Day17:call the base class
    ACL权限
    内置函数
    用户配置文件-影子文件
    用户配置文件-用户信息文件
    脚本安装包
    定义函数
  • 原文地址:https://www.cnblogs.com/hql1117/p/11420389.html
Copyright © 2020-2023  润新知