【发布时间】:2022-01-24 04:19:49
【问题描述】:
class MyClass(Base):
__tablename__ = 'my_table'
id = Column(Integer, primary_key=True)
type_id = Column(String(50))
# map value
type_name = {
"type_id_1":"name_1",
"type_id_2":"name_2"
}
从表 Myclass 查询 type_id 时有没有办法返回“类型名称”?
通过使用@hybrid_property,我非常接近目标
class Myclass(Base):
...
@hybrid_property
def type_name(self):
# The goal is get type_name, but it's not working since self.type_id is not a String object
name = type_name[self.type_id]
return cast(name, String)
-
请查看 stackoverflow.com/a/53700911/2681632 了解如何使用
case
执行SQL 端查找。 -
@Ilja Everilä 太棒了,这正是我想要的,非常感谢。