验证用户是否将过滤器添加到后端Django中的过滤器的正确方法是什么?

时间:2019-05-17 18:11:43

标签: python django

我要一个建议,建议如何检测用户正在使用哪些过滤器,过滤系统可以有不同的选项来获取数据,但是可以使用if语句检查POST中是否包含值,然后添加将其设置为过滤器集并不是一个好选择,特别是当它们很多时。

# Some if statements detecting if a filter is used (if it is not null in the POST)
# Adding the filter to filters

filters = {
# filters after being added
            '{}__{}'.format('categories', 'exact'): request.POST['category'],
            '{}__{}'.format('price', 'gte'): request.POST['price'], # Only an example
        }
        products = Product.objects.filter(**filters)

这可行,但是我只想知道您会推荐什么。

2 个答案:

答案 0 :(得分:2)

如果我正确理解了您的问题,我会改chain filters

queryset = Product.objects.all()

if 'category' in request.POST:
    queryset.filter(categories__exact=request.POST['category'])

if 'price' in request.POST:
    queryset.filter(price__gte=request.POST['price'])

答案 1 :(得分:1)

进一步介绍Gasanov的建议:


possible_filters = {
    'category': 'exact',
    'price': 'gte',
    # etc. Not sure if this can be done any smarter
    # maybe if you pass `cateogry__exact` in the POST data instead of just `category`?
}

queryset = Product.objects.all()
for key, val in request.POST.items():
    if key in possible_filters:
        filter_kwargs = {
            f'{key}__{possible_filters[key]}': val,
        }
        queryset = queryset.filter(**filter_kwargs)

或者您可以建立kwarg并打一个filter。除非您要过滤反向FK关系或M2M关系,否则两者几乎是相同的(当它们不同时的文档是here

filter_kwargs = {}
for key, val in request.POST.items():
    if key in possible_filters:
        filter_key = f'{key}__{possible_filters[key]}'
        filter_kwargs[filter_key] = val
queryset = queryset.filter(**filter_kwargs)