2012-11-22 49 views
12

我想問一個我在SQLAlchemy中遇到的問題,並在寫作時找到了解決方案。我反正它只是爲了以防萬一它有助於某人:)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'))) 

現在我的問題是,我想先過濾由date_out在Post中。我可以這樣得到它:

# assume start_date and end_date 

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

但如何通過標籤在同一時間?

回答

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

聲明:這是我的實際代碼的簡化示例,我可能在簡化時犯了一個錯誤。

我希望它能幫助別人。