Skip to content

Django: Perform GROUP BY over a view queryset

I need to perform group by over a queryset of objects already filtered by standard django filters in order to filter by how many objects in queryset are related to same foreign key object. My code now (does not work):

class CustomerTicketsViewSet(AbstractViewSet):
    queryset = CustomerTicket.objects.all()
    serializer_class = CustomerTicketSerializer

    def filter_queryset(self, queryset):
        queryset = super().filter_queryset(queryset)

        tr2smp = int(self.request.GET.get('tickets_related_to_same_topic_gte', False))
        if self.action == "list" and tr2smp:
             topics_queryset = queryset.values('topic').annotate(tickets_to_same_mp=Count('topic')) #does not work
             queryset = ..... #filter tickets queryset somehow based on topics_queryset
        return queryset

If I filtered over all objects, I could have used


but how can I do the same thing with QuerySet?



Add order_by() to the end of your query:


An interesting documentation about the usage of values() together with an annotation/aggregation can be found here:

User contributions licensed under: CC BY-SA
4 People found this is helpful