Home > OS >  custom filtering not working in django rest framework
custom filtering not working in django rest framework

Time:12-02

i have tried to use custom filtering by defining a filter class and importing in my view but it is not working.

My code:

class ProductAPIView(ListAPIView):
    permission_classes = [AllowAny]
    serializer_class = ProductSerializer
    queryset = Product.objects.all()
    filter_backends = [DjangoFilterBackend]  
    filterset_class = ProductFilter
    pagination_class = CustomPagination

My filter:

class ProductFilter(filters.FilterSet):
   variants__price = filters.RangeFilter()

   class Meta:
      model = Product
      fields = ['brand__name','variants__price','availability','slug','category__name',
                       'services','featured','best_seller','top_rated']

My models:

class Brand(models.Model):    
    name = models.CharField(max_length=100, unique=True)
    featured = models.BooleanField(default=False)


class Product(models.Model):
    
    merchant = models.ForeignKey(Seller,on_delete=models.CASCADE,blank=True,null=True)
    category = models.ManyToManyField(Category, blank=False)
    sub_category = models.ForeignKey(Subcategory, on_delete=models.CASCADE,blank=True,null=True)
    mini_category = models.ForeignKey(Minicategory, on_delete=models.SET_NULL, blank=True, null=True)
    brand = models.ForeignKey(Brand, on_delete=models.CASCADE)
    collection = models.ForeignKey(Collection, on_delete=models.CASCADE)
    featured = models.BooleanField(default=False)  # is product featured?
   

Now when I call localhost/api/products?brand___name__in=lg,sony it doenst filter and shows all the objects from the database. It only works when I dont put in like this localhost/api/products?brand___name=lg .But I need to query through multiple parameters. What is the issue here?? From the docs, it says i can multiple query using __in.

CodePudding user response:

The default lookup_expr is exact if you don't describe one.

Your FilterSet should look like this:

class ProductFilter(filters.FilterSet):
   variants__price = filters.RangeFilter()

   class Meta:
      model = Product
      fields = {
        'brand__name': ['exact', 'in'],
        'variants__price': ['exact'],
        'availability': ['exact'],
        'slug': ['exact'],
        'category__name': ['exact'],
        'services': ['exact'],
        'featured': ['exact'],
        'best_seller': ['exact'],
        'top_rated': ['exact']
      }
  • Related