sqlalchemy objects as dict keys?
The use case is that I have a remote (read slow) database from which I grab some data through ORM mapped classes.
I'd like to store non-db temporary data along side the ORM data and I don't want开发者_Python百科 to pollute the mapped class namespace (which other people use) with a bunch of temporary attributes just so I can store some object specific data. What I would really like to do is to use these as keys into a dict.
I've seen this thread so I know that it can be done, but I don't like the example of:
def __hash__( self ):
return id( self ) if self.id is None else hash( self.id )
Because my use case includes a db set auto_increment primary key which won't exist until after a flush. Potentially changing hashes is one of the no-noes of hashing and I'd like to avoid it.
I could try to fix it if I put a flush in the __hash__
but that feels like way too big a side effect to be a good idea.
So, the question is: is there a good way to use ORM mapped class instances as keys to a dict, or is there another/better way to associate temporary data with an object without polluting it's namespace?
Consider storing your local, "non-db" data in the appropriate mapped instances as a non-mapped attribute. e.g.
local_data = {'batsman': 'Sangakkara', 'bowler': 'swann'}
mapped_instance_from_query._local_data = local_data
SQLAlchemy will simply ignore unmapped attributes.
精彩评论