多对多
表结构的设计
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】
创建多对多的表的方法
- 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') # 描述多对多的关系 不生成字段 生成关系表
- 自己手动创建
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()
- 自己创建 + 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()