On Jun 21, 2013, at 1:49 PM, Chris Withers <
ch...@simplistix.co.uk> wrote:
> On 20/06/2013 20:43, Michael Bayer wrote:
>>
>> On Jun 20, 2013, at 1:43 PM, Chris Withers<
ch...@simplistix.co.uk> wrote:
>>
>>> Digging up an old thread, this time with (I hope) correct terminology:
>>>
>>> If I have a transient object which has had some attributes set on it, what would be the best way to use that object to load an object based on those attributes from the database?
>>>
>>> I didn't noticed a session.lookup(myobj) method ;-)
>>
>>
>> The mapper has all the identity key functions now:
>>
>> from sqlalchemy import inspect
>>
>> def lookup(session, obj):
>> mapper = inspect(obj).mapper
>> return session.query(mapper).get(mapper.primary_key_from_instance(obj))
>>
>>
>> a2 = A(id=1)
>> assert lookup(s, a2) is a1, "%r != %r" % (a1, a2)
>
> That's not what I'm after ;-)
>
> The query needed to get the unit test to pass, as I would currently do it, would be:
>
> def lookup(self):
> return session.query(Model).filter(
> value1=self.value1
> ).one()
>
> ...but I'm looking to generalise that to any attribute that has been set on the transient object on which lookup is called.
oh, it's not the primary key. Well then you'd need to figure out what attributes you care about. If it's all attributes, then loop through inspect(obj).attrs and build up a filter() function:
> To unsubscribe from this group and stop receiving emails from it, send an email to