Compare Difference Between Two Columns In SQLAlchemy ORM
I'm trying to find out how to do something like the answer to this question but using SQLAlchemy. Having a hard time finding how to order query results by the difference between t
Solution 1:
session.query((Table.revenue - Table.loss).label('profit')).order_by('profit desc').all()
For automatically calculate column you can use events
from sqlalchemy import event
class Table(Model):
id = Column(Integer, primary_key=True)
revenue = Column(Integer)
loss = Column(Integer)
profit = Column(Integer)
@event.listens_for(Table.revenue, 'set')
def revenue_listener(target, value, oldvalue, initiator):
# update profit when revenue change
target.profit = value - (target.loss or 0)
@event.listens_for(Table.loss, 'set')
def loss_listener(target, value, oldvalue, initiator):
# update profit when loss change
target.profit = (target.revenue or 0) - value
Post a Comment for "Compare Difference Between Two Columns In SQLAlchemy ORM"