Sqlalchemy 使用 map func 返回列值

分享于2022年07月17日 mysql python sqlalchemy 问答
【问题标题】:Sqlalchemy 使用 map func 返回列值(Sqlalchemy return column value with map func)
【发布时间】: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)



【解决方案1】:

阅读您的问题后,我是这样解释的。你想要这个吗?

class MyClass(Base):
    __tablename__ = 'my_table'
    id = Column(Integer, primary_key=True)
    type_id = Column(String(50))

    def __repr__(self):
        return "" % (self.id, self.type_id)

  • 不完全是,我需要的是: return type_name[self.type_id]