1 多对多关系中,第三张表的建立
-默认使用ManyToMany,自动创建
-使用中介模型
-即手动创建第三张表,又要使用好用的查询
-完全自己写第三张表
# 使用中介模型
class Author(models.Model): nid = models.AutoField(primary_key=True) name = models.CharField(max_length=32) age = models.IntegerField() author_detail = models.OneToOneField(to='AuthorDatail', to_field='nid', unique=True, on_delete=models.CASCADE) class AuthorDatail(models.Model): nid = models.AutoField(primary_key=True) telephone = models.BigIntegerField() birthday = models.DateField() addr = models.CharField(max_length=64) class Book(models.Model): nid = models.AutoField(primary_key=True) name = models.CharField(max_length=32) price = models.DecimalField(max_digits=5, decimal_places=2) publish_date = models.DateField() publish = models.ForeignKey(to='Publish', to_field='nid', on_delete=models.CASCADE) # 当前在哪个表中,元组中的第一个参数就是 表明_id authors=models.ManyToManyField(to='Author',through='AuthorToBook',through_fields=('book_id','author_id')) def __str__(self): return self.name class Publish(models.Model): nid = models.AutoField(primary_key=True) name = models.CharField(max_length=32) city = models.CharField(max_length=32) email = models.EmailField() class AuthorToBook(models.Model): nid = models.AutoField(primary_key=True) book_id = models.ForeignKey(to=Book, to_field='nid', on_delete=models.CASCADE) author_id = models.ForeignKey(to=Author, to_field='nid', on_delete=models.CASCADE) date=models.DecimalField()
# s1.py
import os if __name__ == '__main__': os.environ.setdefault("DJANGO_SETTINGS_MODULE", "day76.settings") import django django.setup() from app01 import models
# 西游记这本书是lqz和egon写的
# book=models.Book.objects.get(pk=1)
# # book.authors.add(1,2) # 用不了了
# # 只能手动写
# models.AuthorToBook.objects.create(book_id_id=1,author_id_id=1)
# models.AuthorToBook.objects.create(book_id_id=1,author_id_id=2)
# 西游记这本书所有的作者
# book = models.Book.objects.get(pk=1)
# res=models.AuthorToBook.objects.filter(book_id=book)
# print(res)
# book = models.Book.objects.get(pk=1)
# print(book.authors.all())
# 西游记这本书是lqz和egon写的 add ,remove, clear,set
# 但是连表操作,book.authors这些都能用
book = models.Book.objects.get(pk=1)
book.authors.add(1,2) # 不能用了