[Django]-Django Postgresql ArrayField aggregation

46👍

In PostgreSQL you can do the following:

SELECT DISTINCT UNNEST(array_column) FROM the_table;

So if your model looks something like

class TheModel(models.Model):
    # ...
    array_field = ArrayField(models.CharField(max_length=255, blank=True),\
                             default=list)
    # ...

the Django equivalent is:

from django.db.models import Func, F
TheModel.objects.annotate(arr_els=Func(F('array_field'), function='unnest'))\
                .values_list('arr_els', flat=True).distinct()
👤Ivan

Leave a comment