【django】django的orm的分组查询

前言:django当中分组查询如何实现?   annotate

from myapp import models
from django.db.models.functions import TruncMonth
from django.db.models import Count,Avg




# 分组  values 就是取值作用
model.Book.objects.values('month').annotate(count=Count('id'))


# 等同于  select month,count(id) from book group by month;

model.Book.objects.values('month').annotate(count=Avg('price'))

# 等同于  select month,avg(price) from book group by month;



# 多表分组

model.A.objects.annotate(a=Avg('B__price')).values('a')

# 等同于select avg(B.price) as a from A join B on A.B_id =B.id group by A.id;

from myapp import models
from django.db.models.functions import TruncMonth
from django.db.models import Count




# 一个日期字段按月分组
 result = model.Book.objects.annotate(month=TruncMonth('date_field')).values('month').annotate(count=Count('id'))

看看这个博主不错

猜你喜欢

转载自blog.csdn.net/legend818/article/details/131088696