我正在尝试通过一个组加入一个字段。我可以按照 one of my previous questions 中的描述在 MySQL 中处理它.但是我现在迁移到 PostgreSQL,建议的解决方案在 PostgreSQL 9.6 中不起作用。 根据Django docs , 可以按照 here 所述使用 StringAgg或 here . 我相信,在较新版本的 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 来计算我需要的内容。 我只是按照他们的 answer 中描述的 Exprator 导入它:
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=',')
)
最佳答案
from django.contrib.postgres.aggregates import StringAgg
这是导入聚合函数的方法
关于python - 如何使用 DjangoORM 在 PostgreSQL 9.6 中使用 StringAgg 聚合函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48353485/