SQLAlchemy: filter many-to-many joinedload

假装没事ソ 提交于 2019-12-12 00:44:48

问题


I have the current table setup for a many to many association between "words" and "phrases":

association_table_wp = Table('words_phras', Base.metadata,
                             autoload=True,
                             extend_existing=True)

class Phrase(Base):
    __tablename__ = 'phrases'
    __table_args__ = {'autoload': True}

    def __init__(self, phrase, explanation=None, active=False):
        self.phrase = phrase
        self.explanation = explanation
        self.active = active

class Word(Base):
    __tablename__ = 'words'
    __table_args__ = {'autoload': True}

    def __init__(self, word, word_id=None, active=False):
        self.word = word
        self.word_id = word_id
        self.active = active

Word.phrases = relationship(Phrase,
                            secondary=association_table_wp,
                            backref="words")

Now normally when I want to look up some words and their phrases I use:

words = db_session.query(Word).filter(Word.id.in_(word_ids)).\
             options(joinedload(Word.phrases)).\
             all()

This allows me to access words[i].phrases to access the phrases associated with a given word.

Now, this works fine, but note that "active" property. I want to filter the words' phrases so that only ones with active == True are returned. How can this be done? I have tried several combinations of joins and eager_loading, but none of them have worked as I'd hope.

Thank you very much.


回答1:


I think contains_eager() is what you're looking for:

words = db_session.query(Word).\
    join(Word.phrases).\
    options(contains_eager(Word.phrases)).\
    filter(Word.id.in_(word_ids)).\
    filter(Phrase.active == True)


来源:https://stackoverflow.com/questions/18268960/sqlalchemy-filter-many-to-many-joinedload

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