@hybrid_property
def balance(self):
plus = sum(op.amount for op in self.operations if op.operation_type in BALANCE_PLUS_OPERATIONS)
minus = sum(op.amount for op in self.operations if op.operation_type in BALANCE_MINUS_OPERATIONS)
return plus - minus
@balance.expression
def balance(cls):
p = select([func.sum(Operation.amount).label('BALANCE_PLUS_OPERATIONS')]) \
.where(Operation.operation_type.in_(BALANCE_PLUS_OPERATIONS)) \
.where(User.id == cls.id) \
.as_scalar()
m = select([func.sum(Operation.amount).label('BALANCE_MINUS_OPERATIONS')]) \
.where(Operation.operation_type.in_(BALANCE_MINUS_OPERATIONS)) \
.where(User.id == cls.id) \
.as_scalar()
return select([p - m]).label('BALANCE')
balance.expression def balance(cls):
работает некорректно
users = User.query.filter_by(balance=51).all()
<User(foo@bar.com)> 51
<User(bar@foor.com)> 0