question answered on irc channel #sqlalchemy Mar 24 11:08:23 <keithgcascio> Let's say I have an sqlalchemy.Table object t (bound to MetaData bound to an engine with an open connection) with a composite primary key defined (so t.primary_key() returns an object of type PrimaryKeyConstraint), and I also have a tuple that represents a specific value of that primary key. Mar 24 11:08:30 <keithgcascio> What is the tersest code (briefest + most elegant) to perform a lookup for a row identified by that key, which will return at most one object, or None if no such row exists? Mar 24 11:10:02 <stepz> do you have it mapped to a class? Mar 24 11:13:58 <stepz> if so, session.query(Cls).get(['col1 value', 'col2 value']) Mar 24 11:14:45 <stepz> otherwise you can create function to create the criterion Mar 24 11:15:00 <stepz> something like this: def pk_criterion(tbl, *values): return and_(*(col == val for col, val in zip(tbl.primary_key, values))) Mar 24 11:15:45 <stepz> so select([t.c.some_col, t.c.some_other_col]).where(pk_criterion(tbl, 'col1 value', 'col2 value')) Mar 24 11:28:24 <keithgcascio> stepz: thanks, I am new to SQLAlchemy, am I correct that having a Table object means that yes, it is mapped to a class? Mar 24 11:28:50 <hylje> a table object is a class in itself Mar 24 11:28:53 <stepz> no, a Table object isn't mapped to anything Mar 24 11:29:01 <keithgcascio> stepz: I see Mar 24 11:29:21 <stepz> going through the tutorials will probably clarify lots of things Mar 24 11:29:51 <keithgcascio> stepz: I like that get() function, I definitely want to use that Mar 24 11:33:19 <keithgcascio> stepz: this looks promising: http://www.sqlalchemy.org/docs/ormtutorial.html#creating-table-class-and-mapper-all-at-once-declaratively Mar 24 11:33:31 <keithgcascio> stepz: "Creating Table, Class and Mapper All at Once Declaratively" Mar 24 11:33:47 <stepz> it's what most people use Mar 24 11:34:58 <keithgcascio> stepz: I want to do table reflection along with declarative Mar 24 11:37:33 <stepz> class Foo(Base): __table__ = Table('foo', Base.metadata, autoload=True) Mar 24 11:39:17 <keithgcascio> stepz: nice, thank you
-- You received this message because you are subscribed to the Google Groups "sqlalchemy" group. To post to this group, send email to [email protected]. To unsubscribe from this group, send email to [email protected]. For more options, visit this group at http://groups.google.com/group/sqlalchemy?hl=en.
