python - 如何在 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()
?
解决方案
我找到了一种解决方法。我使用 Python 导出值,然后将其包装在cast
or中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。想知道是否存在更好的方法
推荐阅读
- ionic-framework - 离子应用程序:谷歌地图 + uiGmapgoogle-maps
- qt - 读取字符串并通过 UART 将二进制文件发送到 STM32
- java - 在服务器上运行 Spring Boot 应用程序
- sql - ORACLE SQL 连接 MULTI SELECT 语句 ORACLE
- python - 如何从日期时间索引中去除时间戳?
- php - php程序准备与关联数组
- javascript - 如何制作成Buffer?- 尝试解码 MessagePack Axios 对 JSON 或 JavaScript 对象表示法的响应
- angular - 具有动态数据的可缩放旭日形(带标签)
- android - 黑屏模拟器 Android Q Preview (Pixel 2)
- json - 如何发出 https 请求?