SQLAlchemy: Passing a Parameter to Object
I am using SQLAlchemy in my project.
I have two classes, call them Bar and Foo
class Bar(object):
def valueize(self, name):
# do some crazy magic
return value
class Foo(Base):
id = Column(...
name = Column(...
@property
def value(self):
return self._bar.valueize(self.name)
Foo is constructed either by me constructing the object directly or by SQLalchemy when it loads Foo objects from the database. But Foo needs a Bar object in order to work. But how do I get the reference to Bar into the Foo?
Normally, I'd just pass the Bar into the Foo constructor. However, that won't work here because SQLAlchemy is creating the object.
What I want to be able to do is somehow configure a Session with a Bar object such that that bar objec开发者_如何转开发t is injected into the Foo objects when they are added to the session.
What I've Tried
SQLAlchemy has an events system. One of the session events is on_attach. This is called whenever an object is added to the session. However, it is not called when an object is loaded from the database.
There are events which are called when loaded from the database, but they are on a per-mapper basis. The Bar object needs to be associated with an individual session.
If you only need one Bar
for all Foo
s, you can use a class property or method in Foo
. Since you haven't taken this obvious path, you seem to need to construct a new Bar
for every new Foo
. Probably instrumentation has the needed events. The caching example has to have a way to intercept load events.
精彩评论