Django分組聚合查詢實(shí)例分享
多表查詢
1. 增刪改
一對多:先一后多,外鍵可以為對象或依賴表的主鍵(publish and book)
publish = Publish.objects.create()Book.objects.create(....publish=publish|publish_id=publish.id)
刪: 默認(rèn)存在級聯(lián)刪除
改: book修改外鍵,外鍵一定存在
多對多:
關(guān)系表的獲取(book(主鍵) and author) book.author
增:book.author.add(作者對象們|主鍵們)
刪: clear()清除 remove() 可刪除單個作者
改: set([作者對象們|主鍵們])
2. 查
基于對象,正向找屬性,反向找類名小寫,多條記錄類名小寫_set
book.publish.first().name (book 一定是對象,不是queryset)publish.book_set.first().name
基于雙下劃線:
Book.objects.filter(id=1).values(’publish__name’)[0] (values 查出的也是queryset)publish.values(’book__name’)
今日內(nèi)容
1. 分組查詢: 聚合結(jié)果 group_by()
2. 聚合函數(shù)
3. 字段
分組查詢(單獨(dú)聚合查詢 and 分組聚合查詢---基于mysql)
Book: id name price publish_date publish
聚合函數(shù)可以單獨(dú)使用 ---- 整張表是一個大組
select max(price) from book
聚合函數(shù)在分組下使用
select max(price) as high_price from book group by publish having high_price > 50;
聚合查詢---基于ORM
聚合函數(shù)的使用場景:
單獨(dú)使用:不分組,只查聚合結(jié)果
分組使用: 按字段分組,可查分組字段與聚合結(jié)果
導(dǎo)入聚合函數(shù):
from django.db.models import Avg,Max,Min,Count,Sum
單獨(dú)聚合查詢:aggregate (聚集,合集)---不分組
# 語法
# 聚合函數(shù): Max, Min,Sum, Avg, Count
aggregate(別名=聚合函數(shù)(’字段‘)
規(guī)則:
1. 可以同時對多個字段進(jìn)行聚合處理: aggregate(name1= , name2= ...)
2. 是QuerySet 對象的方法(all,filter)
3. 返回值為dict類型
4. 在aggregate之前的values操作沒作用,被忽略
例: 所有書中最貴的書的價格
dic = Book.objects.all().aggregate(high_price=max(’price),low_price=min(’price’))
分組聚合查詢: annotate (注釋,做注解) --- 分組
# 語法values(’分組字段’).annotate(別名=聚合函數(shù)(‘字段’).filter(聚合別名條件).values(’取分組字段’,’取聚合字段別名’))
規(guī)則:
1. values --- annotate 分組組合, values控制分組的字段,annotate控制聚合字段
2. values 可以按多個字段分組values(’字段1‘,’字段2‘)
3. 可以同時對多個字段進(jìn)行聚合處理 annotate(別名1=max(’price’),別名2=min(’price’))
4. 分組后的filter 代表having判斷,只對聚合字段進(jìn)行條件判斷,(參數(shù)為非聚合或分組進(jìn)行條件判斷代表where判斷)
5. 取字段值 values() 省略默認(rèn)取所有分組字段和聚合字段,也可以自己定義(對非分組或非聚合字段,該字段自動被變成分組字段)
# 案例:每個出版社出版的最貴的書的價格高于50元的出版社名與最高價格
# 思路:按出版社分組(從book出發(fā)),high_price=max(’price’), filter(high_price__gt=50)
# 每個組的價格最貴的
Book.objects.all().values(’publish__name’).annotate(high_price=max(’price’).filter(high_price__gl=50).values(’publish__name’,’high_price’))
字段屬性
1. null: 默認(rèn)Fasle(默認(rèn)字段不能為空) , True 表示字段可為null2. blank: 默認(rèn)False, True 表示字段可以為空3.choice: 限制了該選項(xiàng)字段值必須是指定的choice 中的一個 (元組套元組)sex = models.SmallIntegerField(choice=((1,’man’),(2,’female’)))obj.get_sex_display()
有choices 這個字段的: 要取得’女‘或’男‘, get_字段名sex_display() --超出失效4. db_column: 自定義字段名db_column=’gender’ 起別名該sex5. db_index : True 設(shè)置索引6. default: 字段默認(rèn)值7. editable: 默認(rèn)為True, False: 不在 admin 界面顯示8. primary_key : TRUE 為主鍵,9. unique: true 字段值不可重復(fù)
字段
1. AutoField(): 默認(rèn)自增主鍵(primary_key=True)2. BooleanField(): 布爾字段, 對應(yīng)database tinyint 類型3. CharField(): 字符類型(默認(rèn)不為空)max_length=20,null=True 可以為空4. DateField(): 年月日auto_now = True 數(shù)據(jù)別更新就會更新時間auto_now_add = True 數(shù)據(jù)第一次產(chǎn)生時5. DateTimeField(): 年月日時分秒auto_now = True 數(shù)據(jù)別更新就會更新時間auto_now_add = True 數(shù)據(jù)第一次產(chǎn)生時6. DecimalField(): 混合精度的小數(shù)類型max_digits = 5, 含小數(shù)為的最大位數(shù)decimal_places = 2 , 小數(shù)位數(shù)7. IntegerField(): 整型
不常用字段
關(guān)系字段
1. ForeignKey(): 外鍵字段to= 關(guān)聯(lián)模型類 (一對多)to_file = 關(guān)聯(lián)字段,省略默認(rèn)關(guān)聯(lián)主鍵on_delete (外鍵關(guān)聯(lián)數(shù)據(jù)被刪除時的操作)models.CASCADE 級聯(lián)刪除modles.PROTECT 拋出異常models.SET_NULL 設(shè)置空值modles.SET_DEFAULT 設(shè)置默認(rèn)值models.SET(value) 自定義值related_name 自定義反向查詢的字段名db_constraint=False, 取消關(guān)聯(lián),但還可以使用鏈表查詢總結(jié): models.ForeignKey(to=’related class name’, null=True,on_delete=models.SET_NULL,db_constraint=False,related_name=’本類名小寫’)2. OneToOneField(): 一對一字段同外鍵3, ManyToManyField() :多對多關(guān)系to = 關(guān)聯(lián)模型類through=關(guān)聯(lián)關(guān)系類through_fields關(guān)聯(lián)關(guān)系表中(本身字段,關(guān)聯(lián)字段)
斷開外鍵關(guān)聯(lián)的ForeignKey使用(一對多,一對一)
# 一對多查詢 ----(publish and book)# 方式一 : 不使用外鍵,在book 中添加 publish_id 屬性# 不在支持Django ORM 鏈表查詢語法
# class Book(models.Model):# name = models.CharField(max_length=20)# publish_id = models.IntegerField(null=True)## class Publish(models.Model):# name = models.CharField(max_length=20)## # 查詢方式:# # 通過第一本書book 找出版社# # id = Book.objects.first().publish_id# # publish = Publish.objects.filter(id=id)[0].name# # print(publish)
方式二:使用外鍵, 用db_constrain=False 字段段開連接# 可以使用Django ORM連表查詢語法class Book(models.Model):name = models.CharField(max_length=20)publish = models.ForeignKey(to=’Publish’,db_constraint=False,null=True,on_delete=models.SET_NULL) # to_field=’id’ 不寫會自動添加
class Publish(models.Model):name = models.CharField(max_length=20)
# 書的出版社 (外鍵方式)# print(Book.objects.first().publish.name)# print(Book.objects.filter(pk=1).values(’publish__name’))
斷開關(guān)聯(lián)--- 多對多自動創(chuàng)建關(guān)系表
# 斷開關(guān)聯(lián)(db_constraint屬性)的多對多自動創(chuàng)建關(guān)系表 (book(外鍵) and author)# 斷開后依然支持Django ORMlianiao 查詢語法# 當(dāng)新表中無需新加額外字段時, 可以自動創(chuàng)建class MyBook(models.Model):name = models.CharField(max_length=20)# 這里會產(chǎn)生第三張表book_author = models.ManyToManyField(to=’MyAuthor’,db_constraint=False)
class MyAuthor(models.Model):name = models.CharField(max_length=20)
# # 查詢方法# # 多對多(自動創(chuàng)建第三張表): 書的作者# b1 = MyBook.objects.first()# # b1.book_author 這個是關(guān)系表# for author in b1.book_author.all():# print(author.name)
# print(MyBook.objects.filter(pk=1).values(’book_author__name’))
斷開關(guān)聯(lián) --- 多對多手動創(chuàng)建關(guān)系表
# 手動創(chuàng)建關(guān)系表的原因: 可以擁有自身字段,可以通過關(guān)系表類名直接獲取第三張表
# 手動創(chuàng)建關(guān)系表可以讓關(guān)系表可以擁有更多的自身的字段,同時通過關(guān)系表類名可以直接獲取第三張表’’’# ****# 1、和自動建立關(guān)系表類似,依然支持Django ORM連表查詢語法(多對多借助關(guān)系表連表查詢)class Book(models.Model):name = models.CharField(max_length=20)class Author(models.Model):name = models.CharField(max_length=20)class Book_Author(models.Model):book = models.ForeignKey(to='Book', null=True, on_delete=models.SET_NULL, db_constraint=False)author = models.ForeignKey(to=’Author’, null=True, on_delete=models.SET_NULL, db_constraint=False)time = models.DateField()’’’
’’’# ****2、手動創(chuàng)建關(guān)系表,在關(guān)系表中用ForeignKey方式支持基于外鍵關(guān)系表的ORM連表查詢,同時明確ManyToManyField字段,所以也支持ORM正向方向連表查詢-- db_constraint=False斷開關(guān)聯(lián)可以在ForeignKey或ManyToManyField任意一方完成class Book(models.Model):name = models.CharField(max_length=20)# 明確through與through_fields,ManyToManyField才不會自動建立關(guān)系表,沒有關(guān)聯(lián)關(guān)系后就不能再使用db_constraint字段屬性author = models.ManyToManyField(to=’Author’, through=’Book_Author’, through_fields=(’book_id’, ’author_id’))class Author(models.Model):name = models.CharField(max_length=20)class Book_Author(models.Model):book = models.ForeignKey(to='Book', null=True, on_delete=models.SET_NULL, db_constraint=False)author = models.ForeignKey(to=’Author’, null=True, on_delete=models.SET_NULL, db_constraint=False)time = models.DateField()’’’# 總結(jié):手動創(chuàng)建第三張表,第三張表的增刪改就采用關(guān)系表類名衍生的create|delete|update,就不再擁有add|clear|remove|set(因?yàn)殛P(guān)系表擁有自己的字段,這些方法無法直接操作這些字段)
到此這篇關(guān)于Django分組聚合查詢實(shí)例分享的文章就介紹到這了,更多相關(guān)Django分組聚合查詢內(nèi)容請搜索好吧啦網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持好吧啦網(wǎng)!
相關(guān)文章:
1. Python如何批量生成和調(diào)用變量2. ASP.NET MVC實(shí)現(xiàn)橫向展示購物車3. ASP.Net Core對USB攝像頭進(jìn)行截圖4. .net如何優(yōu)雅的使用EFCore實(shí)例詳解5. ASP.Net Core(C#)創(chuàng)建Web站點(diǎn)的實(shí)現(xiàn)6. python 爬取京東指定商品評論并進(jìn)行情感分析7. python基礎(chǔ)之匿名函數(shù)詳解8. Python獲取B站粉絲數(shù)的示例代碼9. ajax動態(tài)加載json數(shù)據(jù)并詳細(xì)解析10. 通過CSS數(shù)學(xué)函數(shù)實(shí)現(xiàn)動畫特效
