sqlalchemy在and_ filters中使用生成器

时间:2013-07-15 21:43:07

标签: sqlalchemy generator

我正在尝试搜索,我通过生成器将几个不同的音节传入'and_'函数。然后我的搜索应该返回所有并且只返回所有给出音节的单词

matches = db.session.query(Word).join(Word.syllables).filter(db.and_(Syllable.syllable ==(syl for syl in combo)))。all()

目前不返回任何内容。这种方法是否有意义?

1 个答案:

答案 0 :(得分:0)

我不认为这个查询会做你想要的。对于combo =(1,2):

,您生成的查询将是这样的
SELECT words.* FROM words INNER JOIN syllables ON words.id = syllables.word_id WHERE syllables.syllable = 1 AND syllables.syllable = 2

我认为你想要的是combo =(1,2):

SELECT words.* FROM words INNER JOIN syllables AS s1 ON words.id = s1.word_id AND s1.syllable = 1 INNER JOIN syllables AS s2 ON words.id = s2.word_id AND s2.syllable = 2

重复加入可能会变慢但是在sqlalchemy中你可以这样做:

query = db.session.query(Word)
for syl in combo:
    syl_cls = aliased(Syllable)
    query = query.join(syl_cls, Word.syllables).filter(syl_cls.syllable == syl)
matches = query.all()

如果您正在生成OR子句,那么此查询将更加简单。