在开发网站过程中遇到一个多条件查询,但并不要求全部填写的情况,如下图,可以只填name,也可以四个全部填好。
极端情况下四个字段都不填写,直接查询,此项目中这里不填默认为ALL,查数据库所有。
如果使用if判断,每种情况写一个filter,需要15个判断语句。很麻烦,不美观,且代码可拓展性差。
解决办法是使用一个字典,将不为空的查询参数塞进去,亲测可行。代码如下:
def advancedSearch(request): visit_page_num = int(request.GET.get("page", 1)) symbol = request.POST.get("symbol") species = request.POST.get("species") experiment = request.POST.get("experiment") disease = request.POST.get("disease") # 极端情况下可以都为空的,不定项查询 filter_condition = dict() if symbol != "ALL": filter_condition['symbol'] = symbol if species != "ALL": filter_condition['species'] = species if experiment != "ALL": filter_condition['experiment__contains'] = experiment # 实验 模糊查询 很多个实验里只要包含就查出来 if disease != "ALL": filter_condition['disease'] = disease result_set = Genes.objects.filter(**filter_condition) page, paginator, page_range = page_func(result_set, visit_page_num) return render(request, 'result.html', {"driverSet": page, "paginator": paginator, "visit_page_num": visit_page_num, "page_range": page_range })
代码里page_func()是我的分页方法,这里忽略不看就行了。
标签:get,request,查询,filter,experiment,Django,page,condition,不定 From: https://www.cnblogs.com/isayruby/p/18307372