'Counting distinct elements in Django ArrayField
I have a model defined by
from django.contrib.postgres.fields import ArrayField
class Model(models.Model):
name = models.CharField(max_length=255)
tags = ArrayField(models.CharField(max_length=255))
I would like a way to efficiently grab the count of each distinct element in my tags ArrayField. I put together this piece of code to do try to do that.
Model.objects.annotate(elems=Func(F('tags'), function='unnest')).values_list('elems', flat=True).annotate(c=Count('elems'))
But it returns an error
...aggregate function calls cannot contain set-returning function calls
LINE 1: ...COUNT(unnest("...
^
HINT: You might be able to move the set-returning function into a LATERAL FROM item.
Any ideas on how to make this query work?
Edit
This is the SQL that Django's ORM generates.
SELECT unnest("model"."tags") AS "elems", COUNT(unnest("model"."tags")) AS "c" FROM "model" GROUP BY unnest("model"."tags");
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
