14

如何使用字典而不是方法参数对 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 ''
4

2 回答 2

30

您使用字典来传递关键字参数,如下所示:

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)
于 2013-04-15T15:02:58.417 回答
7

上面的答案是正确的,我建议一些更有效的答案。

request.GET是 QueryDict 只需将其转换为这样的字典

kwargs = dict(request.GET)

现在过滤它

models.Design.objects.filter(**kwargs)

于 2017-01-16T06:14:44.263 回答