Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use StringAgg aggregation functions in PostgreSQL 9.6 using DjangoORM

I am trying to join a field over a group. I could handle it in MySQL as described in one of my previous questions. However I migrated to PostgreSQL now and the proposed solutions does not work in PostgreSQL 9.6. According to Django docs, it is possible to use StringAgg as described here or here. I believe, in newer versions of PostgreSQL I cannot execute the line:

from django.db.models.sql.aggregates import Aggregate as SQLAggregate

Which throws the error:

from django.db.models.sql.aggregates import Aggregate as SQLAggregate
ModuleNotFoundError: No module named 'django.db.models.sql.aggregates'

How can I create my own Aggregate Function using StringAgg?

Update

It seems I dodn't need to modify StringAgg to calculate what I needed. I just imported it as Exprator described in their answer:

from django.contrib.postgres.aggregates import StringAgg

and used it along with values() to group by the query. Since the fields were not string I had to use Cast as well:

from django.contrib.postgres.aggregates import StringAgg
from django.db.models.functions import Cast
from django.db.models import TextField

query.annotate(
        AggregatedType = StringAgg(Cast('Types', TextField()),delimiter=',')
    )
like image 756
Azee Avatar asked Sep 05 '26 07:09

Azee


1 Answers

from django.contrib.postgres.aggregates import StringAgg

this is how you can import the aggregate functions

like image 92
Exprator Avatar answered Sep 06 '26 22:09

Exprator



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!