首页 > 解决方案 > 如何在 SQL Alchemy 中仅将 Python 表达式用作混合属性

问题描述

我有一个 SQL Alchemy 映射:

class Employee(Base):
  __tablename__ = 'employee'

  id = Column(Integer, primary_key=True)
  first_name = Column(String)
  last_name = Column(String)

  @hybrid_property
  def me(self):
    return 'Yes!' if self.first_name == 'ritratt' else 'Nope...'

现在我只想做一个这样的查询: session.query(Employee.me).all()

但它不起作用,因为 SQL Alchemy 需要列或表达式而不是str. 解决方案是使用hybrid_expression但我不想使用表达式。我希望我的映射只使用混合属性。

如何编写一个hybrid_property返回 astr并使用的映射query()

标签: pythonsqlormsqlalchemy

解决方案


我找到了一种解决方法。我使用 Python 导出值,然后将其包装在castor中concat

from sqlalchemy import cast, String

...

@hybrid_property
  def me(self):
    value = 'Yes!' if self.first_name == 'ritratt' else 'Nope...'
    return cast(value, String) # or return concat('', value)

这似乎仍然有点hacky。想知道是否存在更好的方法


推荐阅读