根据可选参数过滤Django中的对象

时间:2014-12-07 12:23:37

标签: python django django-orm

很多时候我发现自己编写的代码类似于:

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

是否有更好,更通用的方法来构建如上所述的查询?

1 个答案:

答案 0 :(得分:3)

如果请求GET中唯一的东西是潜在的查询参数,那么你可以这样做:

query = MyModel.objects.filter(**request.GET)