我正在尝试在 sqlalchemy 和我的 postgres DB 之间添加一个 pylibmc memcached 层。这篇文章谈到了如何做到这一点。但我也想要反向引用(用于从一到多的关系),所以我修改了该帖子的 user_classes.py 来测试它。
我让 UserStatus 从 database.MemcachedORMObject 继承,并在 UserTable.mapper 中添加了一个 backref。但是我在尝试访问反向引用时收到“DetachedInstanceError:父实例未绑定到会话;属性‘用户’的延迟加载操作无法继续”。我正在使用 Flask-SQLAlchemy==0.16、SQLAlchemy==0.8.0b2 和 pylibmc==1.2.3。
class UserStatus(database.MemcachedORMObject):
def __init__(self, name):
self.name = name
UserStatusTable = Table('user_status', METADATA, \
Column('user_status_id', Integer, primary_key=True),
Column('name', String) )
UserStatusTable.mapper = mapper(UserStatus, UserStatusTable)
UserStatusTable.mapper.compile()
class User(database.MemcachedORMObject):
def __init__(self, name, email, password, user_status_id):
self.name = name
self.email = email
self.password = password
self.user_status_id = user_status_id
UserTable = Table('user', METADATA, \
Column('user_id', Integer, primary_key=True),
Column('name', String),
Column('email', String),
Column('password', String),
Column('user_status_id', Integer),
ForeignKeyConstraint(['user_status_id'], ['user_status.user_status_id']) )
UserTable.mapper = mapper(User, UserTable,
properties = { 'user_status': relation(UserStatus, backref='user', lazy=False)})
UserTable.mapper.compile()
尝试访问 backref 时出错:
In [14]: from user_classes import * In [15]: ust = UserStatus.fetch_by_field(UserStatus.user_status_id, 1) Memcached Getting: user_classes.UserStatus:(1) In [16]: ust.user
--------------------------------------------------------------------------- DetachedInstanceError Traceback (most recent call last) <ipython-input-16-38fd625abed9> in <module>()
----> 1 ust.user /home/david/sqlalchemy-memcached/env/lib/python2.7/site-packages/sqlalchemy/orm/attribut es.pyc in __get__(self, instance, owner)
249 return dict_[self.key]
250 else:
--> 251 return self.impl.get(instance_state(instance), dict_)
252
253 /home/david/sqlalchemy-memcached/env/lib/python2.7/site-packages/sqlalchemy/orm/attribut es.pyc in get(self, state, dict_, passive)
543 value = callable_(passive)
544 elif self.callable_:
--> 545 value = self.callable_(state, passive)
546 else:
547 value = ATTR_EMPTY /home/david/sqlalchemy-memcached/env/lib/python2.7/site-packages/sqlalchemy/orm/strategi es.pyc in _load_for_state(self, state, passive) 495 "Parent instance %s is not bound to a Session; "
496 "lazy load operation of attribute '%s' cannot proceed" %--> 497 (orm_util.state_str(state), self.key)
498 )
499 DetachedInstanceError: Parent instance <UserStatus at 0x21e9dd0> is not bound to a Sessi on; lazy load operation of attribute 'user' cannot proceed