Reputation: 19
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?
Upvotes: 0
Views: 479
Reputation: 77092
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()
Upvotes: 1
Reputation: 2276
There are nor a foreign key and a mapper. http://docs.sqlalchemy.org/en/rel_0_9/orm/relationships.html#many-to-many
Upvotes: 0