> -----Original Message----- > From: sqlalchemy@googlegroups.com > [mailto:[EMAIL PROTECTED] On Behalf Of maxi > Sent: 08 February 2008 13:47 > To: sqlalchemy > Subject: [sqlalchemy] Re: Search in object list by field value > > > On 8 feb, 09:58, svilen <[EMAIL PROTECTED]> wrote: > > On Friday 08 February 2008 14:26:04 maxi wrote: > > a) let SQl do it > > p1 = session.query(Person).filter_by(id==123).first() > > #see .filter_by syntax > > Yes, of course, I know it. But my question appoint to how search in an > object list. > > > b) get all people, then plain python: > > for p in people: > > if p.id == 123: break > > else: p=None > > Something like this, but through some build in function. > > Thanks for your replay. > Regards.
I don't think there's anything built in, but it is a very easy stand-alone function to write: ---------------------------------------------------------------- def get_first_match(objects, attrname, value): """ Return the first object where the named attribute has the given value. Returns None if no match is found """ for obj in objects: if getattr(obj, attrname) == value: return obj # Assuming 'people' is a list of Person objects person_one = get_first_match(people, 'id', 1) ---------------------------------------------------------------- Hope that helps, Simon --~--~---------~--~----~------------~-------~--~----~ You received this message because you are subscribed to the Google Groups "sqlalchemy" group. To post to this group, send email to sqlalchemy@googlegroups.com 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 -~----------~----~----~----~------~----~------~--~---