繁体   English   中英

如何在SQLAlchemy中为此混合属性实现SQL级表达式?

[英]How to implement SQL level expression for this hybrid property in SQLAlchemy?

我有一个分类帐表和一个对应的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级别的获取器似乎工作正常。 但是,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而不是其值?

cls.firstname不是“引用值”,而是“ Column 示例中的cls.firstname + " " + cls.lastname沿着以下行生成字符串连接SQL表达式:

firstname || ' ' || lastname

这是混合属性的魔力的一部分:它们使编写可以在两个域中都可以使用的简单表达式相对容易,但是在处理python实例和构建SQL表达式时,您仍然必须了解。

您可以重新考虑一下自己的混合动力,然后在case表达式中将转换选项实际传递给数据库:

from sqlalchemy import func

...

@amountInCAD.expression
def amountInCAD(cls):
    # This builds a list of (predicate, expression) tuples for case. The
    # predicates compare each row's `currency` column against the bound
    # `from_` currencies in SQL.
    exchange_rates = [(cls.currency == from_,
                       # Note that this does not call python's round, but
                       # creates an SQL function expression. It also does not
                       # perform a multiplication, but produces an SQL expression
                       # `amount * :rate`. Not quite sure
                       # why you had the Decimal conversion, so kept it.
                       func.round(cls.amount * Decimal(rate), 2))
                      for (from_, to_), rate in
                      cls.currency_exchange_rate_lookup.items()
                      # Include only conversions to 'CAD'
                      if to_ == 'CAD']
    return case(exchange_rates +  [
        # The default for 'CAD'
        (cls.currency == 'CAD', cls.amount),
    ])

这样,您就可以将汇率查询作为CASE表达式有效地传递给SQL。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM