多对多表之间关系表
models.py文件代码
from django.db import models
# Create your models here.
class Publisher(models.Model):
id = models.AutoField(primary_key=True)
name = models.CharField(max_length=64,null=False,unique=True)
def __str__(self):
return "publisher_name:{}".format(self.name)
class Book(models.Model):
id = models.AutoField(primary_key=True)
title = models.CharField(max_length=128,null=False)
publisher = models.ForeignKey(to=Publisher,related_name="books")
def __str__(self):
return "book_title:{}".format(self.title)
class Author(models.Model):
id = models.AutoField(primary_key=True)
name = models.CharField(max_length=16,null=False)
book = models.ManyToManyField(to="Book")
def __str__(self):
return "author_name:{}".format(self.name)
查询与操作方法代码
import os
if __name__ == '__main__':
#加载Django项目的配置信息
os.environ.setdefault("DJANGO_SETTINGS_MODULE","testinclude.settings")
#导入Django,并启动Django项目
import django
django.setup()
from ormtest import models
#多对多查询
#查询作者(小白),写过的所有书有那些
author_obj = models.Author.objects.get(name="小白")
print(author_obj)
author_obj_books = author_obj.book.all()
print(author_obj_books)
#1.create(为小白作者对象创建一本书)
#首先:在book表中创建一本书,并指定相应的出版社
#然后:在作者和书的多联多系表中,自动添加一条关联记录
author_obj.book.create(title="zabbix从入门到精通",publisher_id=3)
#2.add(为小白作者,添加一本书(网络基础原理))
book_obj = models.Book.objects.get(title="网络基础原理")
author_obj.book.add(book_obj)
#3.remove(为作者小白,删除一本书《网络基础原理》)
#1、为作者小白,删除一本书<网络基础原理>
book_obj = models.Book.objects.get(title="网络基础原理")
author_obj.book.remove(book_obj)
#为作者小白,删除一本书,书的id为4
author_obj.book.remove(4)
#4.clear(把作者为小白的关联的书,全部清空删除)
author_obj.book.clear()