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

标签 python postgresql 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

我希望能够先按时间排序查询,然后按event_type排序。按时间排序非常容易,因为日期时间具有自然排序。然而,按 event_type 排序有点棘手,因为 event_type 可以采用值 receivedopen >完成。我希望所有查询都按照上述指定的顺序按 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>

最佳答案

您可以使用CASE expression来实现您的查找。在 SQL 中:

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 - 如何通过 SQLAlchemy 中的自定义函数进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53695927/

相关文章:

python - 闲置3秒后如何再次移动一圈?

python - 在 Python 中查找最相似的形状

java - 如何使用 preparedstatement 获取最后插入的行的 id?

java - Postgres 查询 - 使用文本类型更新 json 列中的字段

mysql - SqlAlchemy 使用 ORM 截断表

python - 如何在 Altair 中包裹轴标签

python - 定义具有非标准域的多维字段

postgresql - postgres安装数据库集群初始化失败(Postgresql Version 9.4.4)

python - 每次迁移时 Alembic 都会重新创建外键,导致表上出现重复的外键

python - 如何将嵌套属性编码到架构?