SQLAlchemy未运行

2024-05-23 23:47:05 发布

您现在位置:Python中文网/ 问答频道 /正文

我有以下代码:

session = scoped_session(sessionmaker(autocommit=False, autoflush=True, bind=engine))

Base = declarative_base()
Base.query = session.query_property()

class CommonBase(object):
  created_at = Column(DateTime, default=datetime.datetime.now)
  updated_at = Column(DateTime, default=datetime.datetime.now, onupdate=datetime.datetime.now)

class Look(Base, CommonBase):
  __tablename__ = "looks"
  id = Column(Integer, primary_key=True)

  def __init__(self):
    print "__init__ is run"
    Base.__init__(self)
    self.feedback = None

  def set_feedback(self, feedback):
    """Status can either be 1 for liked, 0 no response, or -1 disliked.
    """
    assert feedback in [1, 0, -1]
    self.feedback = feedback

  def get_feedback(self):
    return self.feedback

我得到了以下错误:

^{pr2}$

在我看来,我的__init__方法没有运行,因为我在日志中看不到任何print语句。在

有人能解释一下为什么我的__init__没有运行,我能做些什么?在


Tags: selftruebasedatetimeinitsessiondefcolumn
1条回答
网友
1楼 · 发布于 2024-05-23 23:47:05

查看SQLAlchemy documentation on reconstruction

The SQLAlchemy ORM does not call __init__ when recreating objects from database rows. The ORM’s process is somewhat akin to the Python standard library’s pickle module, invoking the low level __new__ method and then quietly restoring attributes directly on the instance rather than calling __init__.

If you need to do some setup on database-loaded instances before they’re ready to use, you can use the @reconstructor decorator to tag a method as the ORM counterpart to __init__. SQLAlchemy will call this method with no arguments every time it loads or reconstructs one of your instances. This is useful for recreating transient properties that are normally assigned in your __init__:

from sqlalchemy import orm

class MyMappedClass(object):
    def __init__(self, data):
        self.data = data
        # we need stuff on all instances, but not in the database.
        self.stuff = []

    @orm.reconstructor
    def init_on_load(self):
        self.stuff = []

When obj = MyMappedClass() is executed, Python calls the __init__ method as normal and the data argument is required. When instances are loaded during a Query operation as in query(MyMappedClass).one(), init_on_load is called.

相关问题 更多 >