很多时候我发现自己编写的代码类似于:
query = MyModel.objects.all()
if request.GET.get('filter_by_field1'):
query = query.filter(field1 = True)
if request.GET.get('filter_by_field2'):
query = query.filter(field2 = False)
field3_filter = request.GET.get('field3'):
if field3_filter is not None:
query = query.filter(field3 = field3_filter)
if field4_filter:
query = query.filter(field4 = field4_filter)
# etc...
return query
是否有更好,更通用的方法来构建如上所述的查询?
答案 0 :(得分:3)
如果请求GET中唯一的东西是潜在的查询参数,那么你可以这样做:
query = MyModel.objects.filter(**request.GET)