15

我在询问我在 SQLAlchemy 中遇到的问题,并在写作时找到了解决方案。无论如何我都会发布它以防万一它对某人有帮助:)

假设我有一个似乎有效的多对多关系(至少我可以获取孩子) 三个表:posts、tags 和 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))
 )

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

4

1 回答 1

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

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

我希望它可以帮助某人。

于 2012-11-22T16:54:36.063 回答