SQLAlchemy:过滤多对多的joinload

时间:2013-08-16 08:25:54

标签: filter sqlalchemy many-to-many

我有当前的表设置,用于“单词”和“短语”之间的多对多关联:

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

现在通常当我想查找我使用的一些单词和短语时:

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

这允许我访问words[i].phrases以访问与给定单词相关联的短语。

现在,这工作正常,但请注意“活动”属性。我想过滤单词'短语,以便只返回active == True。如何才能做到这一点?我尝试了几种连接和eager_loading的组合,但是没有一种能像我希望的那样工作。

非常感谢。

1 个答案:

答案 0 :(得分:3)

我认为contains_eager()正是您所寻找的:

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