如何使用Dictionary而不是方法参数对Django模型进行过滤? 这就是我在这里:
class StoreView(TemplateView):
def get(self, request):
# A bunch of gets
sort = request.GET.get('sort')
sort_price = request.GET.get('sort_price')
sort_mfr_method = request.GET.get('mfr_method')
# The params tpsort by
sort_params = {}
if sort is not None:
sort_params['sort'] = sort
if sort_price is not None:
sort_params['sort_price'] = sort_price
if sort_mfr_method is not None:
sort_params['sort_mfr_method'] = sort_mfr_method
# The Model Query
design_list = models.Design.objects.filter(sort_params)
# etc...
Side Question,有没有更好的方法设置字典值,而不是我上面做的?比如三元组,但如果不存在价值就不会存在?
sort_params['sort'] = sort if not None else ''
答案 0 :(得分:20)
您使用字典传递关键字参数,如下所示:
models.Design.objects.filter(**sort_params)
没有内置的方法来有条件地设置一个dict键,但如果你这么做,你可以自己编写:
def set_if_not_none(mapping, key, value):
if value is not None:
mapping[key] = value
class StoreView(TemplateView):
def get(self, request):
# A bunch of gets
sort = request.GET.get('sort')
sort_price = request.GET.get('sort_price')
sort_mfr_method = request.GET.get('mfr_method')
# The params tpsort by
sort_params = {}
set_if_not_none(sort_params, 'sort', sort)
set_if_not_none(sort_params, 'sort_price', sort_price)
set_if_not_none(sort_params, 'sort_mfr_method', sort_mfr_method)
# The Model Query
design_list = models.Design.objects.filter(**sort_params)
答案 1 :(得分:5)
上面的答案是正确的,我建议更有效率。
此处request.GET
是QueryDict
只需将其转换为像这样的字典
kwargs = dict(request.GET)
现在过滤它
models.Design.objects.filter(**kwargs)