Django Postgresql ArrayField aggregation

前端 未结 1 1691
栀梦
栀梦 2020-12-11 00:58

In my Django application, using Postgresql, I have a model with an ArrayField of CharFields. I would like to know if there\'s a DB way to aggregate and get a list of all the

相关标签:
1条回答
  • 2020-12-11 02:01

    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()
    
    0 讨论(0)
提交回复
热议问题