首页 文章

如何通过SQLAlchemy中的自定义函数进行排序

提问于
浏览
0

所以我有一个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>

1 回答

  • 1

    您可以在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)
    

    这使用case()构造的value简写来生成一个表达式,该表达式将给定的列表达式与字典中传递的键进行比较,从而产生映射的值作为结果 .

相关问题