简体   繁体   中英

sqlalchemy many-to-many relationship, how to filter the collection

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)

Which I can filter posts by tag: tag.posts , but I cannot filter the posts collection use the expression tag.posts.filter(Post.id > 10).all() such as Django Models.

So how to filter many-to-many collection?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM