SQLAlchemy __init__ not running

后端 未结 1 432
别那么骄傲
别那么骄傲 2021-01-11 16:19

I have the following code:

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

Base = declarative_base()
Base.query = ses         


        
相关标签:
1条回答
  • 2021-01-11 16:51

    Check out the 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.

    0 讨论(0)
提交回复
热议问题