F,Q,aggregate
Posted liuxiaomo
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了F,Q,aggregate相关的知识,希望对你有一定的参考价值。
# models class Student(models.Model): name = models.CharField(max_length=32) age = models.IntegerField() def __str__(self): return self.name
# views # aggregate from django.db.models import F, Q, Count, Avg, Max, Min, Sum def agg_orm(request): if request.method == ‘GET‘: stu = models.Student.objects.aggregate( stu_num = Count(‘age‘), stu_avg = Avg(‘age‘), stu_max = Max(‘age‘), stu_min = Min(‘age‘), stu_sum = Sum(‘age‘) ) print(stu) # 运行结果 :{‘stu_num‘: 24, ‘stu_avg‘: 28.6667, ‘stu_max‘: 41, ‘stu_min‘: 22, ‘stu_sum‘: 688} return HttpResponse(‘ok‘)
#F Q def stu_orm(request): if request.method == ‘GET‘: # F 表达式表示数据库表的某一列至 # F 表达式可以在不实际把数据存入python内存的前提下,引用值和操作数据库 # print(models.Student.objects.all().update(age=F("age") + 1)) # Q 复杂查询,多应用查找 # 可以组合 &(and) |(or) ~(not) 操作 当操作字符用于俩个Q的对象产生一个新的Q对象 # 例如:Q(Q(pk=8) | Q(pk__gt=10)) & Q(name=‘root‘) stus = models.Student.objects.filter( Q(age__gt=1) & Q(age__lt=30), Q(name__startswith=‘tom‘) ) print(‘stu‘, stus) # stu_list = [ # {"name":‘tom‘,‘age‘:11}, # {"name":"nike",‘age‘:12}, # {‘name‘:‘xiaomo‘,‘age‘:30} # ] # # for stu in stu_list: # models.Student.objects.create(**stu) return HttpResponse(‘ok‘)
以上是关于F,Q,aggregate的主要内容,如果未能解决你的问题,请参考以下文章
$Django 聚合函数分组查询F,Q查询orm字段以及参数