您好,登錄后才能下訂單哦!
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()
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。