sqlalchemy多对多的关系,如何过滤集合

时间:2014-09-01 13:26:25

标签: python sqlalchemy

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 Models。

那么如何过滤多对多的集合?

2 个答案:

答案 0 :(得分: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()

答案 1 :(得分:0)