2013-03-05 62 views
0

我下面的構造,這似乎產生所需的SQL:SQLAlchemy的:正確的方式做裸存在查詢

>>> print session.query(exists('1').where(MyTable.name=='x')) 
SELECT EXISTS (SELECT 1 
FROM my_table 
WHERE my_table.name = :name_1) AS anon_1 

然而,當我嘗試用.scalar().all()執行它返回錯誤:

*** UnboundExecutionError: Could not locate a bind configured on SQL expression or this Session

我怎樣才能將它綁定在這個簡單的查詢?我不想做bool(MyTable.query.filter(MyTable.name=='x').first()),因爲它浪費地從桌子上拉回整行。


更新:

我也試過:

>>> session.connection(mapper=MyTable).execute(
     exists('1').where(MyTable.name=='x')) 
StatementError: Not an executable clause 'EXISTS \ 
    (SELECT 1 \nFROM my_table \nWHERE my_table.name = %(name_1)s)' [] 
+0

你應該有這樣一行'session.configure(綁定=引擎)' – sayap 2013-03-06 01:50:07

+0

'session.configure()'拋出錯誤'AttributeError:'function'object has no attribute'configure'' 'session .__ class__'是'sqlalchemy.orm.scoping.ScopedSession' – EoghanM 2013-03-06 10:54:15

+0

聽起來不對。請添加相關代碼,其中構建'session'和運行'session.configure()'的位置。 – sayap 2013-03-06 19:54:34

回答

1

得到它,我認爲:

>>> session.connection(mapper=MyTable).execute(
     select([exists('1').where(MyTable.name=='x')]))