【问题标题】:How can i make OR operator in query params in django rest framework如何在 django rest 框架的查询参数中创建 OR 运算符
【发布时间】:2015-03-22 02:09:52
【问题描述】:

如果我需要在 django rest 中进行过滤,那么我通常会这样做

class ProductFilter(django_filters.FilterSet):
    min_price = django_filters.NumberFilter(name="price", lookup_type='gte')
    max_price = django_filters.NumberFilter(name="price", lookup_type='lte')
    class Meta:
        model = Product
        fields = ['category', 'in_stock', 'min_price', 'max_price']

class ProductList(generics.ListAPIView):
    queryset = Product.objects.all()
    serializer_class = ProductSerializer
    filter_class = ProductFilter

我可以像这样使用

http://example.com/api/products?category=clothing&max_price=10.00

但这会做AND

我怎样才能做到这一点或从 url 之类的

在哪里(category = clothing || max_price = 10)

基本上我应该能够在 URL 中提供所有参数,例如

http://example.com/api/products? AND=[{category: clothing}, {age: 10}], OR=[{age_gte:10}]

【问题讨论】:

    标签: python django filtering django-rest-framework


    【解决方案1】:

    好的,您需要在您的 url 中传递一些标志来检查您是否要执行混合查询。还要给 params 添加前缀,如果在 AND 运算符中应该使用age=20,则添加前缀'and_',它看起来像and_age=20 等等。与 OR 参数相同。

    让我们有这个网址

    http://example.com/api/products?and_category=clothing&and_max_price=10.00&or_age=20&mixed=true
    

    现在,我们的观点。

    class ProductList(generics.ListAPIView):
        queryset = Product.objects.all()
        serializer_class = ProductSerializer
        filter_class = ProductFilter
    
        def get_queryset(self):
            data = self.request.DATA
            mixed_query = data.get('mixed',None)
            
            if not mixed_query:
                return self.queryset
            and_params = {}
            for key in data:
               if 'and_' in key:
                  and_params[key] = data[key]
            
            
            queryset = Products.objects.filter(**and_params)
            for key in self.request.DATA:
                if 'or_' in key:
                  queryset = queryset | Products.objects.filter(key=data[key])
    
            return queryset
    

    注意:自 3.0 版起,request.DATA 已被弃用,取而代之的是 request.data

    【讨论】:

    • 但是如何在查询中传递参数以及系统如何知道哪些参数是AND,哪些是OR。基本上我想通过在查询中传递它们来进行所有过滤。我不会事先知道哪些参数。所以我想概括一下
    • @user3214546 您需要覆盖您的 get_queryset 视图函数,从请求中提取参数并自己进行查询。让我更新我的答案。
    • 感谢您,但我无法对这些字段进行硬编码,因为它们可以是任何 .它应该能够动态地与和或或任何字段
    • @user3214546 这是一个好点;我猜 URL 结构会与嵌套逻辑(在混合 AND 或 OR 时需要)进行斗争。
    • @user3214546 再次检查我的答案,我更新了它,现在你可以使用任何参数了。
    猜你喜欢
    • 2016-02-27
    • 1970-01-01
    • 2019-12-24
    • 1970-01-01
    • 2014-06-28
    • 2011-04-05
    • 2011-07-23
    • 1970-01-01
    • 2017-09-24
    相关资源
    最近更新 更多