2014-09-01 157 views
0
class Tag(Base): 
    __tablename__ = 'tags' 

    id = Column(Integer, primary_key=True, autoincrement=True) 
    slug = Column(String(50), unique=True, nullable=False) 


class Post(Base): 
    __tablename__ = 'posts' 

    id = Column(Integer, primary_key=True, autoincrement=True) 
    title = Column(String(200), unique=True, nullable=False) 
    tags = relationship('Tag', secondary=posts_tags, backref='posts') 
    created_time = Column(Date, default=date.today()) 
    content = Column(Text) 

,我可以按標籤過濾的帖子:tag.posts,但我無法過濾的帖子收集使用表達式tag.posts.filter(Post.id > 10).all()如Django模型。SQLAlchemy的許多一對多的關係,如何過濾收集

那麼如何過濾多對多的集合呢?

回答

1
my_tag = session.query(Tag).get(1) 

# option-1: if data is already loaded into memory 
posts = [post for post in my_tag.posts if post.id > 10] 

# option-2: query database with filter if you have "my_tag" instance 
posts = session.query(Post).with_parent(my_tag).filter(Post.id > 10).all() 

# option-3: query database with filter if you have slug value 
posts = session.query(Post).join(Tag, Post.tags).filter(Tag.slug == "my_slug").filter(Post.id > 10).all()