How can I order by a custom function in SQLAlchemy(如何在SQLAlChemy中按自定义函数排序)
                            本文介绍了如何在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 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中按自定义函数排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
				 沃梦达教程
				
			本文标题为:如何在SQLAlChemy中按自定义函数排序
				
        
 
            
        
             猜你喜欢
        
	     - 如何在 python3 中将 OrderedDict 转换为常规字典 2022-01-01
 - python-m http.server 443--使用SSL? 2022-01-01
 - 沿轴计算直方图 2022-01-01
 - padding='same' 转换为 PyTorch padding=# 2022-01-01
 - 如何将一个类的函数分成多个文件? 2022-01-01
 - 分析异常:路径不存在:dbfs:/databricks/python/lib/python3.7/site-packages/sampleFolder/data; 2022-01-01
 - 使用Heroku上托管的Selenium登录Instagram时,找不到元素';用户名'; 2022-01-01
 - pytorch 中的自适应池是如何工作的? 2022-07-12
 - 如何在 Python 的元组列表中对每个元组中的第一个值求和? 2022-01-01
 - python check_output 失败,退出状态为 1,但 Popen 适用于相同的命令 2022-01-01
 
				
				
				
				