I am using DRF and django-filters to return a list of Tournaments. This has to work with a calendar on the front end so I want to group by the date field and return the initial object. My view:

class TournamentDayCountViewSet(viewsets.ModelViewSet): queryset = Tournament.objects.all() serializer_class = TournamentCalendarSerializer # permission_classes = [permissions.IsAuthenticated] distance_filter_field = "latlng" filter_backends = (DjangoFilterBackend, DistanceToPointFilter, OrderingFilter) filterset_class = TournamentDayCountFilter

class TournamentDayCountFilter(TournamentFilter): def filter_queryset(self, queryset): return ( queryset.annotate( start_date=Trunc("time_stamp", "day", output_field=DateTimeField()) ) .values("start_date") .annotate(tournament_count=Count("id")).order_by() )

and serializer

"""Serialize calendar info only pertinent to displaying count for speed, pagination is very high""" tournament_count = serializers.IntegerField() start_date = serializers.DateTimeField() class Meta: fields = ("tournament_count", "start_date")

This currently returns results like

{ "tournament_count": 1, "start_date": "2019-01-12T00:00:00Z" }, { "tournament_count": 2, "start_date": "2020-01-18T00:00:00Z" },

I suspect I have to do something like

results = defaultdict(list) qs = queryset.annotate( start_date=Trunc("time_stamp", "day", output_field=DateTimeField()) ).annotate(tournament_count=Count("id")).order_by('start_date') for tourney in qs: results[tourney.start_date].append(tourney) return list(results)

But currently that doesn't work. The results I would like are

[ {'2020/01/10': [{'count': 1, tournaments: [...]}, {'2020/01/11': [{'count': 2, tournaments: [...]}, ]

How do I efficiently return results like this so that I don't have to manipulate a regular queryset on the front end?