SQLAlchemy如何按子对多个进行过滤

时间:2012-11-22 16:54:36

标签: python orm sqlalchemy many-to-many filtering

我在SQLAlchemy中遇到了一个问题,并在编写时找到了解决方案。无论如何,我发布它以防万一它可以帮助某人:)

假设我有多对多的关系似乎有用(至少我可以取儿)三个表:帖子,标签和post_tags。

import sqlalchemy as alc

class Tag(Base):
    __tablename__ = 'tags'

    id = alc.Column(alc.Integer, primary_key=True)
    name = alc.Column(alc.String)
    accepted = alc.Column(alc.Integer)

    posts = relationship('Post', secondary=post_tags)



class Post(Base):

    __tablename__ = 'posts'

    id = alc.Column(alc.Integer, primary_key=True)
    text = alc.Column(alc.String)
    date_out = alc.Column(alc.Date)

    tags = relationship('Mistake_Code', secondary=post_tags)

# relational table
post_tags = alc.Table('check_point_mistakes',
                       Base.metadata,
                       alc.Column('post_id', alc.Integer,ForeignKey('posts.id')),
                       alc.Column('tag_id', alc.Integer, alc.ForeignKey('tags.id')))

现在我的问题是我想先在Post中使用date_out进行过滤。我可以这样得到:

# assume start_date and end_date

query = (
            session.query(Post)
                   .filter(Post.date_out.between(start_date, end_date))
 )

但是如何同时按标签过滤?

1 个答案:

答案 0 :(得分:16)

query = (
    session.query(Post)
           .join(Post.tags)     # It's necessary to join the "children" of Post
           .filter(Post.date_out.between(start_date, end_date))
           # here comes the magic: 
           # you can filter with Tag, even though it was not directly joined)
           .filter(Tag.accepted == 1)
)

免责声明:这是我的实际代码的一个减少的例子,我可能在简化时犯了错误。

我希望它有所帮助。