使用SQLAlchemy我想从子查询sq_objects
重现可用的aggregate function jsonb_object_agg:
from sqlalchemy import select, func
s = select([
sq_objects.c.object_id,
func.jsonb_object_agg(
sq_objects.c.keys, sq_objects.c.values).over(
partition_by=sq_objects.c.object_id).label("attributes"),
]).\
distinct(sq_objects.c.object_id)
但是,execute返回:
(psycopg2.ProgrammingError)无法适应类型'方法'
[ SQL: "SELECT DISTINCT ON (sq_objects.object_id)
sq_objects.object_id,
jsonb_object_agg(
%(jsonb_object_agg_1)s,
%(jsonb_object_agg_2)s
) OVER (PARTITION BY sq_objects.object_id) AS attributes
FROM (SELECT ... ) AS sq_objects"
] [
parameters: {'jsonb_object_agg_1': <bound method Properties.keys of <sqlalchemy.sql.base.ImmutableColumnCollection object at 0x7f0ffb7aa828>>,
'jsonb_object_agg_2': <bound method Properties.values of <sqlalchemy.sql.base.ImmutableColumnCollection object at 0x7f0ffb7aa828>>}]
这是我要重现的SQL代码:
SELECT DISTINCT ON (sq_objects.object_id)
sq_objects.object_id,
jsonb_object_agg(
sq_objects.keys,
sq_objects.values
) OVER (PARTITION BY sq_objects.object_id) AS attributes
FROM (SELECT ... ) AS sq_objects
答案 0 :(得分:1)
不是最优雅的实现,但是因为我现在是子查询列的标签;原始text
输入解决了问题:
func.jsonb_object_agg(
text("sq_objects.keys"),
text("sq_objects.values")
).over(
partition_by=sq_objects.c.object_id).label("attributes"),
答案 1 :(得分:1)
问题在于属性keys
和values
是不可变列集合sq_objects.c
的方法。解决该问题的另一种方法是使用项目访问符号来获取实际的列:
func.jsonb_object_agg(
sq_objects.c["keys"],
sq_objects.c["values"]
).over(
partition_by=sq_objects.c.object_id
).label("attributes")