Django过滤器模型由词典 [英] Django Filter Model by Dictionary
本文介绍了Django过滤器模型由词典的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如何使用字典而不是方法参数在Django模型上进行过滤?
这就是我在这里:
How does one do a filter on a Django Model using a Dictionary rather than method arguments? This is what I have right here:
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...
侧面问题,是否有更好的方式设置字典值比上面我在做什么例如三元,但是如果没有这个值就不会存在这个值?
sort_params['sort'] = sort if not None else ''
推荐答案
你使用一个字典传递这样的关键字参数:
You use a dictionary to pass keyword arguments like this:
models.Design.objects.filter(**sort_params)
没有内置的方式有条件地设置一个dict键,但是如果你这样做很多,你可以自己写:
There's no built-in way to conditionally set a dict key, but if you do this a lot, you can write your own:
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)
这篇关于Django过滤器模型由词典的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文