开发者

Consistent application of stuff on __init__ with SqlAlchemy

Suppose I have something like this:

class Tab(Base):
  a = 'a'
  b = 'b'
  c = 'c'

  def __init__(self):
    self.c_a = DBSession.query(Table2).filter(Table2.a == self.a).all()

It seems that self.c_a is only applied on items I insert. I want to ensure that the operations specified in __init__ (this is just an example which is probably better done through relationship()开发者_如何学运维, but use your imagination) apply to all objects, including objects that SA queries out of my database. Anyone know how to do this?

I feel like I might be misunderstanding something, please correct me if so.


referencing the database from inside the model is an abstraction leak; models shouldn't have to know about the particulars of the persistence they may reside on; they might not be persistent at all (they are, after all, models, and might be used for any sort of computation.)

When trying to make associations to other entities, you should always use relationship(), which does work regardless of the presence or absence of an underlying persistence store. What's more, relationships are useful when you are using SQLAlchemy for dynamically generated queries; executing queries in model methods doesn't permit this sort of flexibility.

If you are sure that you need to operate on a session at the model layer (instead of at the controller layer, as you usually should be), then you certainly shouldn't be using a global Session instance; always compute the session from the object itself:

class MyModel(Base):
    def frobnicate(self):
        session = sqlalchemy.orm.Session.object_session(self)
        if session is None:
            raise ValueError("not connected to a session")
        session.query(...)


You are right, when objects are loaded using SA sessions, the __init__ is not called.
To have the code executed also in other cases, please use the Instance Events. I guess that load is of particular use in your situation, but refresh might also be of interest.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜