How to set field name in django aggregate?
For example,
My programs:
[{"name": "html"}, {"name": "css"}, {"name": "css"}, {"name": "css"}]
in database.
models.py
class Program:
name = models.CharField(max_length=50)
views.py
class ProgramCountView(APIView):
def get(self, request):
query_list = []
programs = Program.objects.distinct().values_list("name", flat=True)
for program in programs:
query_list.append(Count("name", filter(Q(name=program)))
result = Program.objects.aggregate(*query_list)
return Response(result)
But error has been: Complex aggregates require an alias.
I want result like {"html": 1, "css": 3}
Use a dictionary to store your counts and unpack them as keyword arguments when passed to aggregate()
class ProgramCountView(APIView):
def get(self, request):
queries = {}
programs = Program.objects.distinct().values_list("name", flat=True)
for program in programs:
queries[program] = Count("name", filter=Q(name=program))
result = Program.objects.aggregate(**queries)
return Response(result)