Question
I created a hybrid property which is composed of a string and a decimal formatted as percentage but I am getting a TypeError when using the hybrid expression. I've tried several variations on the f-string including converting it to float first but I still get the error on the same line. What is the best way to do this string formatting and concatenation on the hybrid property expression?
I want to know why 'result_1' is producing an error, and 'result_2' works correctly
Model
from decimal import Decimal as D
class SupplierDiscount(Base):
__tablename__ = "tblSupplierDiscount"
id = Column(Integer, primary_key=True)
discount = Column(DECIMAL(5, 4), nullable=False)
description = Column(String, nullable=False)
@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
result_1 - Preferred method - but results in error
result_1 = session.query(SupplierDiscount.id.label("SDId"),
SupplierDiscount.disc_desc.label("SDDDesc")
).all()
print('Below is from result_1')
print(result_1)
for i in result_1:
print(i.id, i.disc_desc)
Error produced in result_1
TypeError: unsupported format string passed to BinaryExpression.__format__
result_2 - This works but this is not the preferred method
result_2 = session.query(SupplierDiscount).all()
print('Below is from result_2')
print(result_2)
for i in result_2:
print(i.id, i.disc_desc)
Environment
SQLAlchemy==1.3.20
PostgreSQL 13