如何基于使用SQLAlchemy无法定义一列的两列进行过滤?

时间:2015-02-16 04:16:07

标签: python sqlalchemy

我有一个ShippingRate表,其中包含minimum_price和maximum_price。如果最小值为0且最大值为49,则如果值介于两者之间,则下面的查询将起作用。如果最小值为50美元且未定义最大值,则不起作用。我可以写一个能得到正确结果的查询吗?

db.query(ShippingRate).filter(literal(myVal).between(ShippingRate.minimum, ShippingRate.maximum))

1 个答案:

答案 0 :(得分:1)

假设不存在最小值或最大值,则分别没有最大值或最小值,如果两者都不存在则所有值都为真,那么如下:

from sqlalchemy import and_, or_

db.query(ShippingRate).filter(or_( \
    and_(ShippingRate.minimum == None, ShippingRate.maximum == None), \
    and_(ShippingRate.minimum != None, ShippingRate.maximum != None,  literal(myVal).between(ShippingRate.minimum, ShippingRate.maximum)), \
    and_(ShippingRate.minimum == None, myVal < ShippingRate.maximum), \
    and_(ShippingRate.maximum == None, myVal > ShippingRate.minimum)))