【问题标题】:How to use StringAgg aggregation functions in PostgreSQL 9.6 using DjangoORM如何使用 DjangoORM 在 PostgreSQL 9.6 中使用 StringAgg 聚合函数
【发布时间】:2018-06-29 10:13:01
【问题描述】:

我正在尝试通过组加入一个字段。我可以按照one of my previous questions 中的描述在 MySQL 中处理它。但是我现在迁移到 PostgreSQL,并且建议的解决方案在 PostgreSQL 9.6 中不起作用。 根据Django docs,可以使用herehere 中描述的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=',')
    )

【问题讨论】:

标签: python django postgresql concatenation aggregate-functions


【解决方案1】:
from django.contrib.postgres.aggregates import StringAgg

这是导入聚合函数的方式

【讨论】:

  • 感谢您的回答。我成功导入了 StringAgg。现在我正在创建自定义聚合函数任务。
  • 最终答案可以在问题更新中找到。
  • 有没有办法在 MariaDB 上复制 StringAgg 的功能?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-11-04
  • 2014-01-04
  • 1970-01-01
  • 2021-07-29
相关资源
最近更新 更多