【发布时间】:2017-02-10 23:11:37
【问题描述】:
我有一个分类帐表和一个相应的 python 类。 我使用SQLAlchemy定义了模型,如下,
class Ledger(Base):
__tablename__ = 'ledger'
currency_exchange_rate_lookup = {('CNY', 'CAD'): 0.2}
amount = Column(Numeric(10, 2), nullable=False)
currency = Column(String, nullable=False)
payment_method = Column(String)
notes = Column(UnicodeText)
@hybrid_property
def amountInCAD(self):
if self.currency == 'CAD':
return self.amount
exchange_rate = self.currency_exchange_rate_lookup[(self.currency, 'CAD')]
CAD_value = self.amount * Decimal(exchange_rate)
CAD_value = round(CAD_value, 2)
return CAD_value
@amountInCAD.expression
def amountInCAD(cls):
amount = cls.__table__.c.amount
currency_name = cls.__table__.c.currency
exchange_rate = cls.currency_exchange_rate_lookup[(currency_name, 'CAD')]
return case([
(cls.currency == 'CAD', amount),
], else_ = round((amount * Decimal(exchange_rate)),2))
现在如您所见,我想创建一个名为“amountInCAD”的混合属性。 Python 级别的 getter 似乎工作正常。但是 SQL 表达式不起作用。
现在,如果我运行这样的查询:
>>>db_session.query(Ledger).filter(Ledger.amountInCAD > 1000)
SQLAlchemy 给了我这个错误:
File "ledger_db.py", line 43, in amountInCAD
exchange_rate = cls.currency_exchange_rate_lookup[(currency_name, 'CAD')]
KeyError: (Column('currency', String(), table=<ledger>, nullable=False), 'CAD')
我研究了 SQLAlchemy 关于混合属性的在线文档。 http://docs.sqlalchemy.org/en/latest/orm/mapped_sql_expr.html#using-a-hybrid
将我的代码与示例代码进行比较,我不明白为什么我的代码不起作用。如果在官方示例中,cls.firstname 可以引用一列值,为什么在我的代码中 cls.__table__.c.currency 只返回 Column 而不是它的值?
【问题讨论】:
标签: python sqlalchemy descriptor