【问题标题】:What is the proper way to verify if a filter was used by the user to be added to filters in the backend Django?验证用户是否使用过滤器添加到后端 Django 中的过滤器的正确方法是什么?
【发布时间】:2019-10-05 02:12:27
【问题描述】:

我正在寻求关于如何检测用户正在使用哪些过滤器的建议,过滤系统可以有不同的选项来获取数据,但是使用 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)

这行得通,但我只想知道你会推荐什么。

【问题讨论】:

    标签: python django


    【解决方案1】:

    扩展加萨诺夫的建议:

    
    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)
    

    或者您可以建立 kwargs 并致电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)
    

    【讨论】:

      【解决方案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'])
      

      【讨论】:

      • 是的,但是如果我有太多的过滤器,那将是太多的代码,谢谢你的建议,我喜欢它。
      • 你可以查看这篇帖子stackoverflow.com/a/14958252/924300在django中进行动态查询
      • @Gasanov 只是一个问题,queryset = Product.objects.all() 不会带来整张桌子? (所有数据)然后执行过滤
      • @DanielBurgos 如果您没有附加任何过滤器(如果 POST 为空),它将带来整个表格。但请放心,直到您 try to access it
      • @DanielBurgos 如果你有大量过滤器的应用,你可以查看django-filters
      猜你喜欢
      • 2018-05-15
      • 2020-09-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-01-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多