【问题标题】:Sqlalchemy return column value with map funcSqlalchemy 使用 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)


【问题讨论】:

标签: python mysql sqlalchemy


【解决方案1】:

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

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

    def __repr__(self):
        return "<my_table(id='%s', type_id='%s')>" % (self.id, self.type_id)

【讨论】:

  • 不完全是,我需要的是:return type_name[self.type_id]
猜你喜欢
  • 2014-01-10
  • 2020-12-04
  • 1970-01-01
  • 1970-01-01
  • 2013-10-23
  • 2012-04-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多