【问题标题】:SQLAlchemy: Many-to-Many dynamic loading on both sidesSQLAlchemy:双方的多对多动态加载
【发布时间】:2018-10-17 17:15:37
【问题描述】:

假设我有以下内容:

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 实例中获取所有内容,我可以这样做:

a_stuff_instance.things.filter().all()

因为lazy="dynamic" 部分而查询它。但另一边不起作用。如果我想做

a_thing_instance.stuffs.filter().all()

我收到AttributeError: 'InstrumentedList' object has no attribute 'filter'。我该怎么办?

【问题讨论】:

    标签: python sqlalchemy many-to-many lazy-loading


    【解决方案1】:

    只需将dynamic 也添加到另一边:

    things = relationship(Thing,
                secondary=association_table,
                lazy='dynamic', # *** @note: new parameter ***
                backref=backref("stuffs", uselist=False, lazy='dynamic'))
    

    【讨论】:

    • 我要到星期二才能测试这个,但我会在我测试后回来检查!谢谢。
    猜你喜欢
    • 1970-01-01
    • 2020-11-27
    • 2012-10-11
    • 1970-01-01
    • 1970-01-01
    • 2012-05-13
    • 2011-11-25
    • 2016-09-26
    • 1970-01-01
    相关资源
    最近更新 更多