假设有一个 model 叫 StockModel, 有一个 Integer 型的 remaining 字段,然后有以下操作:
stock = session.query(StockModel).first()
with session.no_autoflush:
try:
stock = StockModel.remaining - 1 # sql: remaining = remaining - 1
# 此时 stock 是 <sqlalchemy.sql.elements.BinaryExpression>
# 若要再对 stock 进行比较,如下:
if stock.remaining > 10:
pass
# 则会直接报错:
# TypeError: Boolean value of this clause is not defined
# 我现在的解决方式是,如果 stock 是 BinaryExpression 的话,就避免
# 进行比较,直接做减法操作,然后在 commit 之后做二次校验。。。
# 如下:
if isinstance(stock.remaining, BinaryExpression):
stock.remaining = StockModel.remaining - (stock.remaining.right.value + decrease_amount)
session.commit()
# 在这里做二次校验:
if stock.remaining < 0:
raise Expression("Stock not enough")
except BaseException:
session.rollback()
finally:
session.close()
请问各位大佬,有没有更优雅的解决方案呢……在 sqlalchemy 的文档里徜徉了许久还是木有找到想要的解决办法……