您所做的任何查询都不会取代原始查询amount
柱子。但是您可以使用以下查询加载另一列:
q = session.query(Transaction,
case([(Transaction.transfer_account_id==1, -1*Transaction.amount)], else_=Transaction.amount).label('special_amount')
)
q = q.filter(or_(Transaction.account_id==1, Transaction.transfer_account_id==1))
这不会仅返回Transaction
对象,而是tuple(Transaction, Decimal)
但如果您希望此属性成为对象的一部分,那么:
自从你的case when ...
函数完全独立于条件WHERE
,我建议您按以下方式更改代码:
1)向你的对象添加一个属性,它的作用是case when ...
检查如下:
@property
def special_amount(self):
return -self.amount if self.transfer_account_id == 1 else self.amount
您还可以完全包装对金额的特殊处理,并提供 setter 属性:
@special_amount.setter
def special_amount(self, value):
if self.transfer_account_id is None:
raise Exception('Cannot decide on special handling, because transfer_account_id is not set')
self.amount = -value if self.transfer_account_id == 1 else value
2)修复您的查询,使其仅包含一个过滤子句or_
子句(看起来您的查询根本不起作用):
q = session.query(Transaction).filter(
or_(Transaction.account_id==1,
Transaction.transfer_account_id==1)
)
# then get your results with the proper amount sign:
for t in q.all():
print q.id, q.special_amount