SQLAlchemy:双方的多对多动态加载

时间:2012-12-07 08:06:13

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

假设我有以下内容:

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'。我该怎么办?

1 个答案:

答案 0 :(得分:3)

只需将dynamic添加到另一方:

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