SQLAlchemy:两侧多对多动态加载 [英] SQLAlchemy: Many-to-Many dynamic loading on both sides
本文介绍了SQLAlchemy:两侧多对多动态加载的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
假设我有以下内容:
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'))
现在,如果我想从Stuff实例中获取所有信息,我可以做:
Now, if I want to get all the things from a Stuff instance I can do:
a_stuff_instance.things.filter().all()
并由于 lazy ="dynamic"
部分对其进行查询.但是,另一端却无法正常工作.如果我想做
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()
我得到 AttributeError:'InstrumentedList'对象没有属性'filter'
.我该怎么办?
推荐答案
也只需在另一侧添加 dynamic
:
things = relationship(Thing,
secondary=association_table,
lazy='dynamic', # *** @note: new parameter ***
backref=backref("stuffs", uselist=False, lazy='dynamic'))
这篇关于SQLAlchemy:两侧多对多动态加载的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文