我尝试使用SQLAlchemy工具箱的关联代理。这是两个相关的模型,映射为一对多关系:
class User(object):
query = db_session.query_property()
def __init__(self, id):
self.id = id
def __repr__(self):
return '{\"id: \"%i}' % (self.id)
class Context(object):
query = db_session.query_property()
def __init__(self, name, user, description=None, private=False):
self.name = name
self.description = description
self.private = private
self.user_id = user
def __repr__(self):
return '{\"id\": %i,\"name\":\"%s\", \"description\":\"%s\", \"private\":\"%r\" }' \
% (self.id, self.name, self.description, self.private)
users = Table('users', metadata,
Column('id',Integer, primary_key=True))
mapper(User, users, properties={
'contexts' : relationship(Context, backref='user', lazy='dynamic')
})
contexts = Table('contexts', metadata,
Column('id', Integer, primary_key=True),
Column('name', String(50), nullable=True),
Column('description', String(255)),
Column('private', Boolean, default=True),
Column('user_id', Integer, ForeignKey('users.id'), nullable=False),
UniqueConstraint('name', 'user_id','private'))
mapper(Context, contexts)})
对于查询,我使用以下内容:
user = User.query.filter(User.id==id)
for context in user.contexts:
context.do_stuff()
但出现以下错误:
AttributeError: 'Query' object has no attribute 'contexts'
答案 0 :(得分:1)
问题的原因是您的关系中的lazy='dynamic'
,它返回一个Query
对象(以便执行其他操作,如过滤/排序等)。要解决此问题,请致电all()
:
user = User.query.filter(User.id==id)
for context in user.contexts.all():
context.do_stuff()