问题
Let's say I have the following:
association_table = Table('things_stuffs', Base.metadata,
autoload=True,
extend_existing=True)
class Thing(Base):
__tablename__ = 'things'
__table_args__ = {'autoload': True}
class Stuff(Base):
__tablename__ = 'stuffs'
__table_args__ = (
{'autoload': True}
)
things = relationship(Thing,
secondary=association_table,
backref=backref("stuffs", uselist=False, lazy='dynamic'))
Now, if I want to get all the things from a Stuff instance I can do:
a_stuff_instance.things.filter().all()
And query it because of the lazy="dynamic"
part. But the other side doesn't work. If I want to do
a_thing_instance.stuffs.filter().all()
I get AttributeError: 'InstrumentedList' object has no attribute 'filter'
. What should I do?
回答1:
Just add dynamic
to the other side as well:
things = relationship(Thing,
secondary=association_table,
lazy='dynamic', # *** @note: new parameter ***
backref=backref("stuffs", uselist=False, lazy='dynamic'))
来源:https://stackoverflow.com/questions/13759188/sqlalchemy-many-to-many-dynamic-loading-on-both-sides