繁体   English   中英

我如何在Django Rest框架的查询参数中使OR运算符

[英]How can i make OR operator in query params in django rest framework

如果我需要在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

我怎样才能做到这一点或从像

其中(category = clothing || max_price = 10)

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

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

Okey,您需要在URL中传递一些标志,以检查是否要执行混合查询。 另外,还要为参数添加前缀,如果在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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM