【问题标题】:SQLAlchemy how to filter by children in many to manySQLAlchemy如何在多对多中按孩子过滤
【发布时间】:2012-11-11 02:43:47
【问题描述】:

我在询问我在 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))
 )

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

【问题讨论】:

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


    【解决方案1】:
    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)
    )
    

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

    我希望它对某人有所帮助。

    【讨论】:

      猜你喜欢
      • 2014-03-12
      • 1970-01-01
      • 2021-08-14
      • 2016-03-14
      • 2013-08-18
      • 1970-01-01
      • 1970-01-01
      • 2012-02-08
      • 2014-05-19
      相关资源
      最近更新 更多