Django viewset annotate in subquery based on filterset field

It seems like this should be a common use case but i cant find an existing answer online.

I am trying to annotate a count based on a query that is filtered using a filterset field in DRF.

class SurveyViewset(viewsets.ModelViewSet):

    entries = models.SurveyEntry.objects.filter(
        survey=OuterRef("id")
    ).order_by().annotate(
        count=Func(F('id'), function='Count')
    ).values('count')

    queryset = models.Survey.objects.annotate(
        total_entries=Subquery(entries)
    ).all().order_by("id")
    serializer_class = serializers.SurveySerializer

    filter_backends = (
        SurveyQueryParamsValidator,
        CaseInsensitiveOrderingFilter,
        django_filters.DjangoFilterBackend,
        SearchFilter,
    )

    filterset_fields = {
        "surveyaddressgroup": ("exact",),
    }

I have surveys and I want to count the number of SurveyEntry based on a a particular address group.

I.e. I ask a survey in a several shopping centres, and I want to see the results when i only choose 1 particular centre to show. At the moment, I get total count regardless of filter the main query.

How can i make the subquery take the filterset choice into account?

Back to Top