简体   繁体   中英

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=',')
    )
from django.contrib.postgres.aggregates import StringAgg

这就是导入聚合函数的方法

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM