python - 如何通过 SQLAlchemy 中的自定义函数进行排序
问题描述
所以我有一个如下所示的 SQLALchemy 模型
from sqlalchemy import (create_engine, Column, BigInteger, String,
DateTime)
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.ext.hybrid import hybrid_property
Base = declarative_base()
class Trades(Base):
__tablename__ = 'trades'
row_id = Column(BigInteger, primary_key=True, autoincrement=True)
order_id = Column(String)
time = Column(DateTime)
event_type = Column(String)
@hybrid_property
def event_type_to_integer(self):
return dict(received=0, open=1, done=2)[self.event_type]
@event_type_to_integer.expression
def event_type_to_integer(self):
pass
我希望能够先订购查询,time
然后再订购event_type
。按时间排序很容易,因为日期时间具有自然排序。但是排序event_type
有点棘手,因为event_type
可以取值received
,open
和done
. 我希望我的所有查询都按照event_type
上述指定的顺序对查询进行排序。看来我需要使用我在上面开始做的混合属性,但是要使order_by
功能正常工作,我似乎还需要编写
@event_type_to_integer.expression
def event_type_to_integer(self):
pass
功能。这是我画一个空白的地方。有没有人有关于如何编写这个函数来完成上述操作的建议。我试过阅读文档和类似的 StackOverflow 帖子。还是有问题。以供参考。这是我要开始工作的查询
sess = Session()
orders = (
sess
.query(Trades)
.order_by(Trades.time.asc(), Trades.event_type_to_integer.asc())
.all()
)
sess.close()
它正在抛出一个
KeyError: <sqlalchemy.orm.attributes.InstrumentedAttribute object at 0x7fcb11861048>
解决方案
您可以使用SQL中的CASE
表达式实现查找:
from sqlalchemy import case
_event_type_lookup = dict(received=0, open=1, done=2)
class Trades(Base):
...
@hybrid_property
def event_type_to_integer(self):
return _event_type_lookup[self.event_type]
@event_type_to_integer.expression
def event_type_to_integer(cls):
return case(_event_type_lookup, value=cls.event_type)
这使用构造的value
简写case()
来生成一个表达式,该表达式将给定的列表达式与字典中传递的键进行比较,产生映射的值作为结果。
推荐阅读
- python-3.x - 如何对已经分组的栏进行分组?
- windows - 我正在尝试查看此脚本的结果,当它运行时它会立即关闭并且不显示用户添加的组
- apache-kafka - 如何处理过期的生产者批次
- python - Sphinx 文档,自动模块的“缩短路径”
- javascript - 将字符串传递给 new Date() 构造函数会导致日期无效
- linux - 如何使用 Curl 将日志文件保存到 Mongodb 服务器
- java - 根据客户端 URL 启用 Spring Security 身份验证
- webp - 即使在实施不同的图像格式之后,Google PSI 也会发出“以下一代格式提供图像”警告
- r - 使用托管在闪亮服务器中的多个应用程序访问相同的数据
- python - 整个数据库是浮动的,它会导致报告问题