Unable to filter using django-filters

I have a models.py which looks like this

class Product(models.Model):
    name = models.CharField(max_length = 255, unique = True, null = False, blank = False)
    brand = models.ForeignKey(Brand, on_delete = models.SET_NULL, null = True, blank = True, related_name = 'products')

class Brand(models.Model):
    name = models.CharField(max_length = 255, unique = True, null = False, blank = False)

I want to filter the data of Products based on name field of Brand model. My views.py looks like this

class ProductAPIView(generics.GenericAPIView):

    serializer_class = ProductSerializer
    queryset = Product.objects.all()
    filter_backends = (DjangoFilterBackend,)
    filterset_class = ProductFilter
    
    def get(self, request):
        products = self.filter_queryset(self.get_queryset())
        serializer = self.serializer_class(products, many = True)
        return Response(serializer.data)

My filters.py looks like this

class ProductFilter(FilterSet):

    class Meta:
        model = Product
        fields = {
            'brand__name' : ['iexact', ]
        }

Whatever query params i send for brand, it results with the entire list instead of filtering the required list.
Is there something i’m missing out here ? Thanks in advance

>Solution :

You should filter with:

?brand__name__iexact=mybrand

It however is probably better to make a dedicated field, like:

from django_filters import CharFilter


class ProductFilter(FilterSet):
    brand = CharFilter(field_name='brand__name', lookup_expr='iexact')

    class Meta:
        model = Product
        fields = {}

then you filter with:

?brand=mybrand

Leave a Reply