如何将十进制格式设置为字符串作为@hybrid_property.expression 的一部分?

问题描述

问题

我想创建一个混合属性,它由一个字符串和一个格式为百分比字符串的十进制组成,但我收到了一个类型错误。我已经尝试了 f 字符串的几种变体,包括首先将其转换为浮点数,但我仍然在同一行上得到错误。在混合属性表达式上进行此字符串格式化和连接的最佳方法是什么?

类型错误

Exception has occurred: TypeError
conversion from InstrumentedAttribute to Decimal is not supported

sqlAlchemy 模型

from decimal import Decimal as D
class supplierdiscount(Base):
    __tablename__ = "tblsupplierdiscount"
    __table_args__ = (UniqueConstraint('supplier_id','subProduct_id','description','discount','dateEffStart',name='supplierdiscount_uc'),{'schema': 'management'})
    id = Column(Integer,primary_key=True,unique=True,nullable=False)
    supplier_id = Column(Integer,ForeignKey(
        'management.tblsupplier.id'),nullable=False)
    subProduct_id = Column(Integer,ForeignKey(
        'management.tblSubProduct.id'),nullable=False)
    discount = Column(DECIMAL(5,4),nullable=False)
    description = Column(String,nullable=False)
    dateEffStart = Column(DateTime,default=datetime.utcNow,nullable=False)
    dateEffEnd = Column(DateTime)
    isactive = Column(Boolean,nullable=False,default=1)
    supplier = relationship(
        'supplier',foreign_keys=[supplier_id])
    subProduct = relationship(
        'SubProduct',foreign_keys=[subProduct_id])

    
    @hybrid_property
    def disc_desc(self):
        return f'{self.description}: {(self.discount * 100):.4f}%'


    @disc_desc.expression
    def disc_desc(cls):
        return f'{cls.description}: {(cls.discount * 100):.4f}%' # Error generated here
        # Exception has occurred: TypeError
        # conversion from InstrumentedAttribute to Decimal is not supported

环境

sqlAlchemy==1.3.20
Postgresql 13

可能是相关问题

我提出了另一个问题 here,但我不确定这两者是否相关。

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)