Python 如何使用Djangorm在PostgreSQL 9.6中使用StringAgg聚合函数
我试图加入一个领域而不是一个团体。我可以在MySQL中处理它,如中所述。但是我现在迁移到了PostgreSQL,建议的解决方案在PostgreSQL 9.6中不起作用。 根据,可以使用所述或所述的StringAgg。 我相信,在较新版本的PostgreSQL中,我无法执行以下命令:Python 如何使用Djangorm在PostgreSQL 9.6中使用StringAgg聚合函数,python,django,postgresql,concatenation,aggregate-functions,Python,Django,Postgresql,Concatenation,Aggregate Functions,我试图加入一个领域而不是一个团体。我可以在MySQL中处理它,如中所述。但是我现在迁移到了PostgreSQL,建议的解决方案在PostgreSQL 9.6中不起作用。 根据,可以使用所述或所述的StringAgg。 我相信,在较新版本的PostgreSQL中,我无法执行以下命令: from django.db.models.sql.aggregates import Aggregate as SQLAggregate 这会引发错误: from django.db.models.sql.agg
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来计算我所需要的。
我刚将其作为Experator导入他们的:
并将其与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?文件当然在这里,这就是我的想法@马布克洛森雷德:谢谢你的回答。我成功导入了StringAgg。现在我正在创建自定义聚合函数任务。最终答案可以在问题的更新中找到。
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