Reputation: 1148
I try to use the association proxy of the SQLAlchemy toolbox. These are the two concerning models, mapped for a one-to-many relation:
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)})
For querying I use the following:
user = User.query.filter(User.id==id)
for context in user.contexts:
context.do_stuff()
But the following error appears:
AttributeError: 'Query' object has no attribute 'contexts'
Upvotes: 0
Views: 1112
Reputation: 77072
The cause of the problem is the lazy='dynamic'
on your relationship, which returns a Query
object (so that additional operations like filtering/ordering etc) can be performed. To solve this, just call all()
:
user = User.query.filter(User.id==id)
for context in user.contexts.all():
context.do_stuff()
Upvotes: 1