[Django]-How do I make a list of field values on annotated Django queryset results?

5👍

Solution for PostgreSQL grouping by name field in combination with ArrayAgg and the distinct=True flag:

from django.contrib.postgres.aggregates.general import ArrayAgg
from django.db.models import Count

Model.objects.values('name').annotate(
    count_total=Count('count'),
    site_list=ArrayAgg('site', distinct=True),
)

1👍

If you are using postgres you can use ArrayAgg

docs – https://docs.djangoproject.com/en/2.2/ref/contrib/postgres/aggregates/

You can use values to group by and something like the following should do the trick. Model.objects.values('name').distinct().annotate(site_list=ArrayAgg('site'), count_total=Count('count'))

👤hancho

Leave a comment