On Jan 23, 2014, at 9:06 PM, Chung <chun...@gmail.com> wrote:

> Hi all,
> 
> Suppose I have a text query like: 
> 
> # intentionally arbitrary string
> textquery = "SELECT count(*) FROM Address a WHERE a.user_id = :user_id"
> 
> And I'm trying to incorporate it into an ORM query on a table User, counting 
> the number of Users with an Address, roughly like so:
> 
> # wrong!
> session.query(User).filter(sqlalchemy.text(textquery).as_scalar() > 0).count()
> 
> But I need to correlate / bindparam / do something to say that the ":user_id" 
> in textquery should be bound to User.id.
> 
> Is this possible?

there’s a few things going on there like text() doesn’t have an as_scalar() 
method, but you can pass in bound parameters to the ultimate SQL that’s 
generated using query.params(user_id=<some id>).

But if you intend for this to be more like a join on the User table, e.g. 
“WHERE a.user_id = user.id” without a specific value, you can’t use bound 
parameters for that.   You’d need to write out your text SQL so that it refers 
exactly to the “user.id” column as the enclosing query() is rendering it.   




Attachment: signature.asc
Description: Message signed with OpenPGP using GPGMail

Reply via email to