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

3👍

Okey, you need to pass in your url some flag to check if you want to perform a mixed query. Also add a prefix to params, if age=20 should be used in the AND operator, add prefix ‘and_’, it looks like and_age=20 and so on. The same for OR params.

Let’s have this url

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

Now, our view.

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

NOTE: request.DATA has been deprecated in favor of request.data since version 3.0

👤levi

Leave a comment