I have a declarative table defined like this:
class Transaction(Base):
__tablename__ = "transactions"
id = Column(Integer, primary_key=True)
account_id = Column(Integer)
transfer_account_id = Column(Integer)
amount = Column(Numeric(12, 2))
...
The query should be:
SELECT id, (CASE WHEN transfer_account_id=1 THEN -amount ELSE amount) AS amount
FROM transactions
WHERE account_id = 1 OR transfer_account_id = 1
My code is:
query = Transaction.query.filter_by(account_id=1, transfer_account_id=1)
query = query.add_column(case(...).label("amount"))
But it doesn’t replace the amount column.
Been trying to do this with for hours and I don’t want to use raw SQL.
Any query you do will not replace original
amountcolumn. But you can load another column using following query:This will not return only
Transactionobjects, but rathertuple(Transaction, Decimal)But if you want this property be part of your object, then:
Since your
case when ...function is completely independent from the condition inWHERE, I would suggest that you change your code in following way:1) add a property to you object, which does the
case when ...check as following:You can completely wrap this special handling of the amount providing a setter property as well:
2) fix your query to only have a filter clause with
or_clause (it looks like your query does not work at all):