Below should do the trick:
q = sess.query(Post).filter(
and_(
Post.tags.contains(tag2),
Post.tags.contains(tag3),
)
).all()
You can replace and_
with or_
if you wish as well add as many as you want.
However, I do not think that you want to search for Posts of specific tag, I think you want to find post which have specific tag name(s)
. If this is the case, you should do:
# get all Posts with has a least one tag from the list ["aa", "bb"]
q = sess.query(Post).filter(Post.tags.any(Tag.name.in_(["aa", "bb"])))
# get all Post with all of the tags in the list ["aa", "bb"]
q = sess.query(Post).filter(
and_(
Post.tags.any(Tag.name.in_(["aa"])),
Post.tags.any(Tag.name.in_(["bb"])),
)
)