F对象
- 可以获取到自己的属性值
- 实现自己的属性自己的属性关联的复杂条件
- 支持运算
Q对象
- Q对象实际上是对条件的一个封装
- 封装后支持逻辑运算
- 与或非
- &
- |
- ~
- 支持嵌套
例子
from django.db.models import Max, Avg, F, Q
from django.http import HttpResponse
from django.shortcuts import renderfrom App.models import Jor, Grade, Newsdef get_jors(request):# jors = Jor.objects.filter(news__n_content__contains="NBA").distinct("j_name")# 想要实现去重jors = Jor.objects.filter(news__n_content__contains="NBA")# jors 四个对象 两个1 两个3jor_list = list()for jor in jors:# print(id(jor))if jor not in jor_list:jor_list.append(jor)return render(request, "JorList.html", context=locals())def get_age(request):result = Jor.objects.aggregate(Avg("j_age"))print(result)return HttpResponse("获取最大年龄成功")def get_grade(request):# grades = Grade.objects.filter(g_girl_num__gt=F("g_boy_num") + 25)# grades = Grade.objects.filter(g_girl_num__gt=1).filter(g_girl_num__lt=20)# grades = Grade.objects.filter(Q(g_girl_num__gt=1) & Q(g_girl_num__lt=20))# grades = Grade.objects.filter(g_girl_num__lt=1).filter(g_girl_num__gt=20)# grades = Grade.objects.exclude(g_girl_num__gte=1).exclude(g_girl_num__lte=20)grades = Grade.objects.filter(Q(g_girl_num__lt=1) | Q(g_girl_num__gt=20))return render(request, "GradeList.html", context=locals())```