創(chuàng)新互聯(lián)公司專業(yè)為企業(yè)提供酒泉網(wǎng)站建設(shè)、酒泉做網(wǎng)站、酒泉網(wǎng)站設(shè)計(jì)、酒泉網(wǎng)站制作等企業(yè)網(wǎng)站建設(shè)、網(wǎng)頁(yè)設(shè)計(jì)與制作、酒泉企業(yè)網(wǎng)站模板建站服務(wù),十年酒泉做網(wǎng)站經(jīng)驗(yàn),不只是建網(wǎng)站,更提供有價(jià)值的思路和整體網(wǎng)絡(luò)服務(wù)。
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項(xiàng)目的配置信息
os.environ.setdefault("DJANGO_SETTINGS_MODULE","testinclude.settings")
#導(dǎo)入Django,并啟動(dòng)Django項(xiàng)目
import django
django.setup()
from ormtest import models
#多對(duì)多查詢
#查詢作者(小白),寫(xiě)過(guò)的所有書(shū)有那些
author_obj = models.Author.objects.get(name="小白")
print(author_obj)
author_obj_books = author_obj.book.all()
print(author_obj_books)
#1.create(為小白作者對(duì)象創(chuàng)建一本書(shū))
#首先:在book表中創(chuàng)建一本書(shū),并指定相應(yīng)的出版社
#然后:在作者和書(shū)的多聯(lián)多系表中,自動(dòng)添加一條關(guān)聯(lián)記錄
author_obj.book.create(title="zabbix從入門到精通",publisher_id=3)
#2.add(為小白作者,添加一本書(shū)(網(wǎng)絡(luò)基礎(chǔ)原理))
book_obj = models.Book.objects.get(title="網(wǎng)絡(luò)基礎(chǔ)原理")
author_obj.book.add(book_obj)
#3.remove(為作者小白,刪除一本書(shū)《網(wǎng)絡(luò)基礎(chǔ)原理》)
#1、為作者小白,刪除一本書(shū)<網(wǎng)絡(luò)基礎(chǔ)原理>
book_obj = models.Book.objects.get(title="網(wǎng)絡(luò)基礎(chǔ)原理")
author_obj.book.remove(book_obj)
#為作者小白,刪除一本書(shū),書(shū)的id為4
author_obj.book.remove(4)
#4.clear(把作者為小白的關(guān)聯(lián)的書(shū),全部清空刪除)
author_obj.book.clear()