如何在SQLAlChemy中按自定义函数排序 [英] How can I order by a custom function in SQLAlchemy

查看:37
本文介绍了如何在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可以接受值receivedopendone。我希望我的所有查询按上述指定顺序按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 expression实现查找:

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()生成一个表达式,该表达式将给定列表达式与字典中传递的键进行比较,从而生成映射值作为结果。

这篇关于如何在SQLAlChemy中按自定义函数排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆