我正在尝试将一组字段连接到一个字段上。在MySQL中,我可以按照我的之前的问题中所述的方式处理它。但是现在我已经迁移到PostgreSQL,并且提出的解决方案在PostgreSQL 9.6中不起作用。 根据Django文档,可以使用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在他们的答案中描述的导入即可:
from django.contrib.postgres.aggregates import StringAgg
我使用values()和group by语句对查询进行分组,并且由于字段不是字符串类型,所以我还需要使用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=',')
)