一:annotate
from django.db.models import Count
q = Blog.objects.annotate(Count('entry'))
#The name of the first blog
q[0].name # 'adfasfa'
#The number of entries on the first blog
q[0].entery_count #42
Blog
模型本身并没有定义 entry__count
属性,但是通过使用关键字参数来指定聚合函数,可以控制注解的名称:
q = Blog.objects.annotate(number_of_entries=Count('entry'))
#The number of entries on the first blog ,using the name provided
q[0].number_of_entries # 42
二:alias
与 annotate() 相同,但不是注解中的 QuerySet
对象,而是保存表达式,以便以后与其他 QuerySet
方法重复使用
#如果你想找到有 5 个条目以上的博客,但对确切的条数不感兴趣,你可以这样做
form django.db.models import Count
blogs = Blog.objects.alias(entries=Count('entry')).filter(entries__gt=5)
三:F()
filter
都
#查出所有评论数大于 pingbacks 的博客条目
from django.db.models import F
Entry.objects.filter(number_of_comments__gt=F('number_of_pingbacks')
是将模型字段值与常量做比较,F()是将模型字段值与同一模型中的另一字段