8
我試圖定義一個混合類簡單的getter/setter方法,我打算在我的數據庫使用的模式:的SQLAlchemy:吸氣劑聲明混合類/ setter方法
from sqlalchemy import Column, Integer, create_engine
from sqlalchemy.orm import synonym, scoped_session, sessionmaker
from sqlalchemy.ext.declarative import declarative_base, declared_attr
engine = create_engine('sqlite:///')
Base = declarative_base(bind=engine)
Session = scoped_session(sessionmaker(bind=engine))
class Mixin(object):
_attr = Column('attr', Integer)
@property
def attr(self):
return self._attr
@attr.setter
def attr(self, value):
self._attr = value
attr = synonym('_attr', descriptor=attr)
class DummyClass(Base, Mixin):
__tablename__ = 'dummy'
id = Column(Integer, primary_key=True)
Base.metadata.create_all()
if __name__ == '__main__':
session = Session()
testobj = DummyClass()
session.add(testobj)
testobj.attr = 42
assert testobj.attr == 42
當我嘗試運行這個例子,我得到以下錯誤:
sqlalchemy.exc.InvalidRequestError: Mapper properties (i.e. deferred,column_property(), relationship(), etc.) must be declared as @declared_attr callables on declarative mixin classes.`
我的代碼幾乎是1:從SQLAlchemy Declarative Tutorial 1份,與物業/同義詞是在混合類中聲明的唯一區別。將「@declared_attr」裝飾器追加或預先添加到現有的裝飾器不會改變任何內容。
我該如何解決這種情況?
謝謝你,是沒有的伎倆:-)這是,如果你依靠語法糖太多了,不學習如何離不開它會發生什麼:3 – jbaiter 2011-04-28 17:09:17
大,很高興它的工作爲ya! – samplebias 2011-04-28 17:13:27