SQLalchemy:在两列或更多列中选择满足条件的行

时间:2021-06-17 12:26:02

标签: python sqlalchemy

我有一个类似于这个模型的 SQLAlchemy 模型(带有底层 SQLite)(我正在使用的模型的精简版):

class Variant(Base):

    __tablename__ = "variants"

    variant_id = Column(Integer, primary_key=True)
    freq1 = Column(Float, nullable=False)
    freq2 = Column(Float, nullable=False)
    freq3 = Column(Float, nullable=False)
    freq4 = Column(Float, nullable=False)

我需要选择(使用 ORM)那些在至少两列中频率大于 1% (0.01) 的 variant_id

所以,像这样的假设记录

1    0.1   0   0.0025 0.001

不会被选中

一个喜欢

670   0.5    0.01 0.001 0

反而会被接走。

我的问题是我不太清楚使用 ORM 的正确方法是什么。

到目前为止,我已经使用 case 进行了“欺骗”,但它看起来有点丑陋且不直接(灵感来自 T-Sql: Select Rows where at least two fields matches condition):

from sqlalchemy import case

condition1 = case([(Variant.freq1 >= 0.01), 1], _else=0)
condition2 = case([(Variant.freq2 >= 0.01), 1], _else=0)
condition3 = case([(Variant.freq3 >= 0.01), 1], _else=0)
condition4 = case([(Variant.freq4 >= 0.01), 1], _else=0)

condition = (condition1 + condition2 + condition3 + condition4) >= 2

result = session.query(Variant).filter(condition).with_entities(Variant.variant_id)

但是它看起来有点笨重,并且基本上一遍又一遍地重复相同的条件。是否有更清晰的解决方案(使用 SQLite,这是我正在使用的)?

0 个答案:

没有答案
相关问题