python - SQLAlachmey : ORM filter to match all items in a list, 没有

标签 python python-2.7 python-3.x sqlalchemy

我想搜索 SQLAlachmey 列表(通过关联表)并通过过滤器匹配其中的多个项目。

我已经评论了this question但我希望仅通过 ORM 过滤器来完成此操作(第二个答案不是通过关联表)。

数据库表设置:

tag_ast_table = Table('tag_association',
                  Base.metadata,
                  Column('file_id', Integer, ForeignKey('files.id')),
                  Column('tag_id', Integer, ForeignKey('tags.id')),
                  PrimaryKeyConstraint('file_id', 'tag_id'))


class File(Base):
    __tablename__ = 'files'

    id = Column(Integer, primary_key=True)
    tags = relationship("Tag", secondary=tag_ast_table)

class Tag(Base):
    __tablename__ = 'tags'

    id = Column(Integer, primary_key=True)
    tag = Column(String)

当前过滤器匹配任何我想修改以匹配所有:

query = db.query(File).filter(File.tags.any(Tag.tag.in_(my_list))).all()

最佳答案

在 SQL 中(在您的链接中提到)一个合理的方法是使用 having count(distinct tags.id) = <your number of tags> .

所以查询需要两件事:它需要一个 in查找您的标签列表,它需要 having寻找存在的完整计数。

query = (
    session.query(File)
    .join(File.tags)
    .filter(Tag.tag.in_(search_tags))
    .group_by(File)
    .having(func.count(distinct(Tag.id)) == len(search_tags))
)

作为边缘情况,如果 search_tags是一个空列表,您不会得到任何结果,所以最好先检查一下。

关于python - SQLAlachmey : ORM filter to match all items in a list, 没有,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35414358/

相关文章:

python - Matplotlib 内存不足

python - Django - 暂停/停用帐户 N 秒

python - 如何在 Process() 中中断 Queue.get()?

Python Shutil 模块复制树

python - 如何在 Eclipse 中突出显示 python 缩进

python - AbstractBaseUser 电子邮件作为用户名验证

python - 如何使用 python 通过 mtime 组织文件夹内的图像

python - 如何使用 python 在 MacOS 上设置代理设置

python - 在使用 python 写入时从日志文件中读取

python - 忽略验证 SSL 证书 python 套接字