如何使用字典而不是方法参数对 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...
附带问题,有没有比我上面做的更好的设置字典值的方法?例如三元,但如果它不存在,则会使该值不存在?
sort_params['sort'] = sort if not None else ''
最佳答案
您可以使用字典来传递关键字参数,如下所示:
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)
关于Django 按字典过滤模型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16018497/