[Django]-Applying a Django FilterSet to an Annotated QuerySet?

8👍

Change get_queryset() method to

def get_queryset(self):
    return Author.objects.annotate(num_books=Count('books')

and define that field in Filter class as

class AuthorFilter(FilterSet):
    num_books = filters.NumberFilter(name='num_books')
    class Meta:
        model = Author
        fields = ['num_books',]#other fields

then use the api as /api/end/point/authorlist/?num_books=10

EXAMPLE

models.py

from django.db import models


class Sample(models.Model):
    foo = models.IntegerField()
    bar = models.IntegerField()

views.py

from django.db.models import F
from django_filters import rest_framework as filters


class MySampleAPI(viewsets.ModelViewSet):
    filter_backends = (filters.DjangoFilterBackend,)
    filter_class = SampleFilterClass
    serializer_class = SampleSerializerClass

    def get_queryset(self):
        return Sample.objects.annotate(foo_bar_sum=F('foo') + F('bar'))

filters.py

from django_filters import rest_framework as filters


class SampleFilterClass(filters.FilterSet):
    sum = filters.NumberFilter(name='foo_bar_sum', lookup_expr='gte')

    class Meta:
        model = Sample
        fields = ['sum', ]
👤JPG

1👍

JPG’s answer worked for me, but I had to replace name by label in the Filter Class:

class AuthorFilter(FilterSet):
    num_books = filters.NumberFilter(label='num_books')  # here
    class Meta:
        model = Author
        fields = ['num_books',]#other fields

Leave a comment