前言python
前言:北京生活好累,想把房子賣了帶上本身喜歡的菇涼一塊兒去旅遊,但是房東不肯意啊,因此仍是學Django吧
aggreate聚合查詢,結果是普通字典,queryset的結束符 from django.db.models import Avg,Max,Min,Count,Sum 求出孩子中間歲數最大的是誰 obj=models.Children.objects.all().aggreate(a=max('age')) print(obj) '結果': 4 Children.objects.aggregate(Avg('age'), Max('age'), Min('age'))
'分組查詢: group by app01_children.wifes_id 每一個妻子生的最大的孩子 方式一: ret=models.Children.objects.values(childs_id).annotate(m=Max('age')) 總結: values寫在annotate前面,意思是以values括號內的字段做爲分組的依據,annotate裏面是你要作的統計結果, 這樣,返回結果爲queryset類型數據,裏面是字典{'childs_id':1,'m':3} 方式二: ret=models.Wife.objects.annotate(m=Max('children__age').values('m','name') 總結:annotate直接寫下了objects後面,意思是按照前面表的全部數據(默認是id值)做爲分組數據,結果返回的是前面這個表的全部models對象(model對象中包含了每一個對象本身的統計結果),在經過values來取值,取值時能夠直接寫字段和統計結果的別名,也是queryset類型,裏面是字典{'m':1,'name':'熊一'} 放過胡斌 就來個圖書館管理系統吧 models.Book.objects.values('authors__name','authors__id').annotate(m=Max('price')) # group by authors__name,authors__id print(ret) ret = models.Author.objects.annotate(m=Max('book__price')).values('name','m') print(ret)
```python
查詢結果是本表中兩個字段的比較滯後符合條件的結果集
查詢一下點贊數大於評論數的全部書籍
list1=[]
books=models.Book.objects.all()
for i in books:
if i.dianzan > i.comment:
list1.append(i)mysql
ret=models.Book.objects.filiter(dianzan__gt=F('comment')).values('title') '大於'
ret = models.Book.objects.filter(dianzan__lt=F('comment')).values('title') '小於
```sql
# 查詢一下點贊大於300或者價錢小於300的書,Q的鏈接符:& -- and, |--or,~ -- not 取反 # ret = models.Book.objects.filter(Q(dianzan__gt=300)|~Q(price__lt=500),xx='oo').values('title') ret = models.Book.objects.filter(Q(dianzan__gt=300)).values('title') # # ret = models.Book.objects.filter(Q(Q(dianzan__gt=300)|~Q(price__lt=500))&Q(xx='oo')).values('title') # print(ret) Q查詢可以進行各類複雜條件的拼接
# 方式1 # ret = models.Book.objects.raw('select * from app01_book;') # for i in ret: # print(i.title) # print(ret) #方式2 django自帶的鏈接通道(配置的pymysql) from django.db import connection import pymysql # conn = pymysq.connect() # cursor = connection.cursor() # cursor.execute('select * from app01_book;') # print(cursor.fetchall()) # # 方式3 pymysql # conn = pymysql.connect( # host='127.0.0.1', # port=3306, # user='root', # password='123', # database='orm02', # charset='utf8' # # ) # cursor = conn.cursor(pymysql.cursors.DictCursor) # cursor.execute('select * from app01_book;') # print(cursor.fetchall())
鎖: models.Book.objects.select_for_update().filter(id=1) 事務: 方式1 全局配置 DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'mxshop', 'HOST': '127.0.0.1', 'PORT': '3306', 'USER': 'root', 'PASSWORD': '123', "ATOMIC_REQUESTS": True, #全局開啓事務,綁定的是http請求響應整個過程中的sql } } 方式2: 視圖函數加裝飾器 from django.db import transaction @transaction.atomic def viewfunc(request): # This code executes inside a transaction. do_stuff() 方式3: 上下文加裝飾器 from django.db import transaction def viewfunc(request): # This code executes in autocommit mode (Django's default). do_stuff() with transaction.atomic(): #保存點 # This code executes inside a transaction. do_more_stuff() do_other_stuff()