【发布时间】:2018-06-29 10:13:01
【问题描述】:
我正在尝试通过组加入一个字段。我可以按照one of my previous questions 中的描述在 MySQL 中处理它。但是我现在迁移到 PostgreSQL,并且建议的解决方案在 PostgreSQL 9.6 中不起作用。 根据Django docs,可以使用here 或here 中描述的StringAgg。 我相信,在较新版本的 PostgreSQL 中,我无法执行以下行:
from django.db.models.sql.aggregates import Aggregate as SQLAggregate
哪个会引发错误:
from django.db.models.sql.aggregates import Aggregate as SQLAggregate
ModuleNotFoundError: No module named 'django.db.models.sql.aggregates'
如何使用StringAgg 创建自己的聚合函数?
更新
看来我不需要修改 StringAgg 来计算我需要的东西。 我刚刚将其导入为 Exprator,在他们的 answer 中描述:
from django.contrib.postgres.aggregates import StringAgg
并将它与 values() 一起使用以按查询分组。由于字段不是字符串,我也必须使用 Cast:
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=',')
)
【问题讨论】:
-
你试试PostgreSQL的exists string_agg吗?文档在这里postgresql.org/docs/current/static/functions-aggregate.html
-
当然,这就是我的想法。 @MabuKloesen
标签: python django postgresql concatenation aggregate-functions