On Sep 1, 2010, at 10:50 AM, Kent wrote: > I'm looking for a way to load mapped attributes for a *Transient* > object. (I've actually needed exactly this several times... it is a > recurring need.) Say I have an object and have no intention at this > point of adding it to the database (so it is not Persistent or even > Pending), but the local side of the foreign key attributes are > populated for a specific attribute or collection. I would like to get > the same SQL or Query that sqla would render if this were a Persistent > object and a lazy loaded attribute. > > For example, say I had an Order object which has a lazily loaded > Customer relationship. > > for a persistent ord object, I say: > > ord.customer > > and sqlalchemy issues "SELECT customers.customerid ... > FROM customers > WHERE customers.customerid = :param_1" > {'param_1': '7'} > > If ord were Transient, but ord.customerid were set to "7", then I > would like to get the Query object that returns the above SQL, despite > this being a Transient object, so I can manually populate this > attribute. > > Thanks very much in advance.
Here's the problem with that. You have some object with no association to any session, and therefore no transaction. Yet you want x.y to emit a query to the database. What context should this query be executed under ? If you're looking for an ad-hoc connection from the connection pool, you can certainly do that but SQLA could never make that decision for you (well if you used SQLA 0.2 it would, but that was a different time....). So here perhaps there is actually a Session at play. Why don't you want to add this object to the Session so that its pending and can do what it needs ? A common reason is because emiting a Query means autoflush is going to kick in and try to INSERT the object before its ready. For that we suggest either getting a hold of the related things ahead of time, or disabling autoflush. This is easy to do and we have recipes to plug it into "with" here: http://www.sqlalchemy.org/trac/wiki/UsageRecipes/DisableAutoflush But going back to your initial request, if you have customerid 7, just session.query(Customer).get(7). That's the simplest way here. When you're transient, you're looking to populate ord.customer with something, not as much have it magically figure itself out with some "pre-flush" kind of behavior. -- You received this message because you are subscribed to the Google Groups "sqlalchemy" group. To post to this group, send email to sqlalch...@googlegroups.com. To unsubscribe from this group, send email to sqlalchemy+unsubscr...@googlegroups.com. For more options, visit this group at http://groups.google.com/group/sqlalchemy?hl=en.