一、应用场景
假设我们现在有一个客房系统,前端界面上展示出来了所有客房的所有信息。用户通过客房的价格、面积、人数等对客房进行模糊搜索,如检索出价格在50到100元之间的客房,同时检索面积在20平方米到30平方米之间的客房,此时后端可以借助Q对象对客房进行筛选处理,并返回给前端。
二、代码部分
学习笔记以注释的形式出现
python
from django.db.models import Q
def searchHouse(request):
datas = request.POST
type = datas.get("type")
area = datas.get("area")
price = datas.get("money")
people = datas.get("people")
query = Q()
# 使用Q对象组合多个查询条件
type_value = int(type)
if type_value != 0:
query.add(Q(type=type_value-1), Q.AND)
if area == "1":
# 若area检索类型为"1",则为检索面积在0到15之间的客房
query &= Q(area__range=(0, 15))
# 给query添加上该查询语句
elif area == "2":
query &= Q(area__range=(15, 20))
elif area == "3":
query &= Q(area__range=(20, 30))
elif area == "4":
query &= Q(area__gte=30)
if price == "1":
query &= Q(price__range=(0, 50))
elif price == "2":
query &= Q(price__range=(50, 100))
elif price == "3":
query &= Q(price__range=(100, 200))
elif price == "4":
query &= Q(price__gte=200)
if people == "1":
query.add(Q(people=1), Q.AND)
elif people == "2":
query.add(Q(people=2), Q.AND)
elif people == "3":
query &= Q(people__gte=3)
# 依照query对house表进行检索
reses = house.objects.filter(query)
houses = []
for res in reses:
a_house = {
"id": res.id,
"type": res.type,
"area": res.area,
"price": res.price,
"people": res.people,
"counts": res.counts,
"status": res.status,
"manager_phone": res.managerID.phone,
"manager_name": res.managerID.name
}
houses.append(a_house)
return JsonResponse({'data': houses}, safe=False)