SQLAlchemy: Many-to-Many dynamic loading on both sides

只愿长相守 提交于 2021-02-08 10:50:48

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!