我无法理解这些表达方式。如何使以下代码工作?
class OperationType(Enum):
MINUS = 1
MINUS_CORR = 2
PLUS = 3
PLUS_CORR = 4
按类型分组操作
BALANCE_PLUS_OPERATIONS = [
OperationType.PLUS.value,
OperationType.PLUS_CORR.value
]
BALANCE_MINUS_OPERATIONS = [
OperationType.MINUS.value,
OperationType.MINUS_CORR.value
]
操作模型
class Operation(Model):
__tablename__ = 'operation'
id = db.Column(db.BigInteger, primary_key=True)
created_at = Column(db.DateTime, nullable=False, default=dt.datetime.utcnow)
operation_type = db.Column(db.SmallInteger, nullable=False)
amount = Column(db.Integer, nullable=False)
user_id = db.Column(db.ForeignKey('users.id'), nullable=False)
user = relationship('User', backref='operation', uselist=False)
用户模型
class User(UserMixin, Model):
__tablename__ = 'users'
id = Column(db.Integer, primary_key=True)
operations = relationship("Operation", backref="users")
@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')
表达式错误,会产生错误的结果:
users = User.query.filter_by(balance=51).all()
for u in users:
print(u, u.balance)
打印:
<User(foo@bar.com)> 51
<User(bar@foor.com)> 0
但我只期望一条记录:
<User(foo@bar.com)> 51
由于
答案 0 :(得分:1)
我将从上下文假设这些方法属于User
类。在那光明中
.where(User.id == cls.id) \
实际上是
.where(User.id == User.id) \
或只是where(True)
,所以每个用户都加入了每个操作,当它可能是类似
.where(Operation.user_id == cls.id) \
虽然由于缺乏榜样而无法说出来。如果确实发生了错误的连接,它解释了查询返回其他用户的原因:它与属于正确用户的操作连接在一起。
您可能还需要添加
.correlate(cls) \
在as_scalar()
之前。我认为最外层的选择也是多余的。你应该能够
return (p - m).label('BALANCE')