from django.db import models # 定義做者模型 class Author(models.Model): name = models.CharField(max_length=100, unique=True) age = models.IntegerField() email = models.EmailField() class Meta: db_table = 'author' def __str__(self): return "%s,%s,%s" % (self.name,self.age, self.email) # 定義出版社模型 class Publisher(models.Model): name = models.CharField(max_length=100,unique=True) class Meta: db_table = 'publisher' # 定義圖書模型 class Book(models.Model): name = models.CharField(max_length=100, unique=True) pages = models.IntegerField() price = models.FloatField() rating = models.FloatField() author = models.ForeignKey('Author', on_delete=models.CASCADE) publisher = models.ForeignKey('Publisher', on_delete=models.CASCADE) class Meta: db_table = 'book' # 定義預約圖書的模型 class BookOrder(models.Model): book = models.ForeignKey('Book', on_delete=models.CASCADE) price = models.FloatField() class Meta: db_table = 'book_order'
from django.http import HttpResponse from .models import Author,Publisher,Book,BookOrder from django.db.models import Avg,Count,Sum from django.db import connection def index(request): # 4.求全部圖書的數量,由於book表中的數據具備惟一性因此能夠經過計算ID的惟一性來計算圖書的數量。 count = Book.objects.aggregate(book_count=Count('id')) print(count) # 打印出結果爲:{'book_count': 4} return HttpResponse("success !")
from django.http import HttpResponse from .models import Author,Publisher,Book,BookOrder from django.db.models import Avg,Count,Sum from django.db import connection def index(request): # 5.求同一種書的預約數量,一樣仍是針對book表,此處能夠是針對bookorder__id,也能夠是bookorder。默認就是針對book__order表中id字段進行操做 books = Book.objects.annotate(books_count=Count('bookorder')) # print(type(books)) # <class 'django.db.models.query.QuerySet'> # 遍歷QuerySet for book in books: print("%s,%s" % (book.name,book.books_count)) # 打印出結果: # 三國演義,2 # 水滸傳,2 # 紅樓夢,2 # 西遊記,0 # 打印出原生SQL語句 print(connection.queries) # 打印出結果:[{'sql': 'SELECT @@SQL_AUTO_IS_NULL', 'time': '0.000'}, {'sql': 'SET SESSION TRANSACTION ISOLATION LEVEL READ COMMITTED', 'time': '0.000'}, {'sql': 'SELECT `book`.`id`, `book`.`name`, `book`.`pages`, `book`.`price`, `book`.`rating`, `book`.`author_id`, `book`.`publisher_id`, COUNT(`book_order`.`id`) AS `books_count` FROM `book` LEFT OUTER JOIN `book_order` ON (`book`.`id` = `book_order`.`book_id`) GROUP BY `book`.`id` ORDER BY NULL', 'time': '0.000'}] return HttpResponse("success !")
from django.http import HttpResponse from .models import Book from django.db.models import Count def index(request): # 6.求被預約的書都有多少種書 # 首先可使用annotate()進行分組,以後對分組的數據進行刪除相同的數據操做。 book_nums = Book.objects.annotate(book_nums=Count('bookorder', distinct=True)) print(book_nums) return HttpResponse("success !")
打印出的結果爲QuerySet對象,不容易分辨具體的數據信息。所以咱們能夠對Book模型的__str__(self)方法進行重寫。python
<QuerySet [<Book: Book object (1)>, <Book: Book object (2)>, <Book: Book object (3)>, <Book: Book object (4)>]>
# 定義出版社模型 class Publisher(models.Model): name = models.CharField(max_length=100,unique=True) class Meta: db_table = 'publisher' def __str__(self): return " ->:%s" % self.name # 定義圖書模型 class Book(models.Model): name = models.CharField(max_length=100, unique=True) pages = models.IntegerField() price = models.FloatField() rating = models.FloatField() author = models.ForeignKey('Author', on_delete=models.CASCADE) publisher = models.ForeignKey('Publisher', on_delete=models.CASCADE) class Meta: db_table = 'book' def __str__(self): return "(書名:%s,頁數:%s,價格:%s,打折:%s,做者:%s,出版社:%s)" % (self.name, self.pages, self.price, self.rating, self.author, self.publisher)
<QuerySet [ <Book: (書名:三國演義,頁數:893,價格:129.0,打折:0.8,做者:羅貫中,47,312587329@qq.com,出版社: ->:清華大學出版社)>, <Book: (書名:水滸傳,頁數:983,價格:159.0,打折:0.75,做者:施耐庵,57,1924572@qq.com,出版社: ->:吉林大學出版社)>, <Book: (書名:紅樓夢,頁數:1543,價格:199.0,打折:0.85,做者:曹雪芹,42,123521472@qq.com,出版社: ->:浙江大學出版社)>, <Book: (書名:西遊記,頁數:1003,價格:159.0,打折:0.75,做者:吳承恩,34,193452272@qq.com,出版社: ->:清華大學出版社)> ]>