dougalg
dougalg

Reputation: 564

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

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?

Upvotes: 1

Views: 1511

Answers (1)

van
van

Reputation: 76962

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'))

Upvotes: 3

Related Questions