首页 > 解决方案 > hybrid_property 在 if/else 中引发 TypeError

问题描述

我想对混合属性中的 id 进行一些格式化,以便 10 以下的数字以 P0 为前缀(P01、P02、03 等)。以下代码TypeError: Boolean value of this clause is not defined__bool__elements.py 中的方法抛出一个。我错过了什么?

在我的models.py中:

@hybrid_property
def conversion_number(self):
    return 'P0{}'.format(self.id) if self.id < 10 else 'P{}'.format(self.id)

标签: pythonpython-3.xsqlalchemy

解决方案


这是我的修复:

@property
def conversion_number(self):
    return 'P0{}'.format(self.id) if self.id < 10 else 'P{}'.format(self.id)

当 sqlalchemy 初始化模型时,问题似乎是 id 是 InstrumentedAttribute(不是 int)。这种行为很奇怪,因为我的实现与 SQLAlchemy 文档中的示例没有本质区别。


推荐阅读