row_to_json的语法与sqlalchemy

时间:2016-05-03 16:59:39

标签: python json postgresql sqlalchemy postgresql-9.2

我想弄清楚如何使用Postgres' (9.2)使用SqlAlchemy的row_to_json。但是,我还没有能够提出任何有效的语法。

details_foo_row_q = select([Foo.*]
    ).where(Foo.bar_id == Bar.id
).alias('details_foo_row_q')

details_foo_q = select([
    func.row_to_json(details_foo_row_q).label('details')
]).where(details_foo_row_q.c.bar_id == Bar.id
).alias('details_foo_q')

如果可能的话,我最好不要输入表格模型中的每个字段。

得到了' mn'

的答案

它应该是更像这样的东西:

details_foo_row_q = select([Foo]).where(Foo.bar_id == Bar.id).alias('details_foo_row_q')

details_foo_q = select([
    func.row_to_json(literal_column(details_foo_row_q.name)).label('details')
]).select_from(details_foo_row_q).where(
    details_foo_row_q.c.bar_id == Bar.id
).alias('details_foo_q')

谢谢你,工作得很棒!

1 个答案:

答案 0 :(得分:2)

您的查询生成错误的SQL

SELECT row_to_json(SELECT ... FROM foo) AS details
FROM (SELECT ... FROM foo) AS details_foo_row_q

应该是

SELECT row_to_json(details_foo_row_q) AS details
FROM (SELECT ... FROM foo) AS details_foo_row_q

您需要使用select literal_column

from sqlalchemy.sql.expression import literal_column

details_foo_q = select([
    func.row_to_json(literal_column(details_foo_row_q.name)).label('details')
]).select_from(details_foo_row_q).where(
    details_foo_row_q.c.bar_id == Bar.id
).alias('details_foo_q')