Python 搜索多对多关系
在sqlalchemy中,如何在多对多关系中搜索列表。在下面的例子中,我想搜索包含一组标签的帖子。我可以搜索包含特定标签的帖子,但不能搜索标签列表:Python 搜索多对多关系,python,sqlalchemy,flask-sqlalchemy,Python,Sqlalchemy,Flask Sqlalchemy,在sqlalchemy中,如何在多对多关系中搜索列表。在下面的例子中,我想搜索包含一组标签的帖子。我可以搜索包含特定标签的帖子,但不能搜索标签列表: class Post(Base): __tablename__ = 'posts' id = Column(Integer, primary_key=True) text = Column(Text) tags = relationship('Tag', secondary=tagmap, backref=
class Post(Base):
__tablename__ = 'posts'
id = Column(Integer, primary_key=True)
text = Column(Text)
tags = relationship('Tag', secondary=tagmap, backref='posts')
def __init__(self, id, text, tags):
self.id = id
self.text = text
self.tags = tags
class Tag(Base):
__tablename__ = 'tags'
id = Column(Integer, primary_key=True)
name = Column(String)
def __init__(self, id, name):
self.id = id
self.name = name
def postsTest():
tag1 = Tag(1, "aa")
tag2 = Tag(2, "bb")
tag3 = Tag(3, "cc")
sess.add(tag1)
sess.add(tag2)
sess.flush()
post = Post(1, "blah:", [tag1, tag2, tag3])
sess.add(post)
sess.flush()
# this works
for p in sess.query(Post).filter(Post.tags.contains(tag1)).all():
print str([tag.name for tag in p.tags])
#this doesn't
for p in sess.query(Post).filter(Post.tags.contains([tag2, tag3])).all():
print str([tag.name for tag in p.tags])
postsTest()
下面应该可以做到这一点:
q = sess.query(Post).filter(
and_(
Post.tags.contains(tag2),
Post.tags.contains(tag3),
)
).all()
如果愿意,您可以将和
替换为或
,也可以添加任意数量
但是,我不认为您想要搜索特定标签的帖子,我认为您想要查找具有特定标签名的帖子。如果是这种情况,您应该执行以下操作:
# 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"])),
)
)
是的,任何的都是我需要的!