Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading