使用SQLAlchemy获取第一个和最后一个元素

时间:2014-10-23 12:38:41

标签: python database postgresql sqlalchemy flask-sqlalchemy

在我的Python(Flask)代码中,我需要获取第一个元素,最后一个元素按照SQLAlchemy查询中的给定变量进行排序。

我首先编写了以下代码:

first_valuation = Valuation.query.filter_by(..).order_by(sqlalchemy.desc(Valuation.date)).first()
# Do some things
last_valuation = Valuation.query.filter_by(..).order_by(sqlalchemy.asc(Valuation.date)).first()
# Do other things

由于这些查询对于PostgreSQL数据库来说可能很重,并且因为我复制了我的代码,我认为只使用一个请求会更好,但我不知道SQLAlchemy是否足够... (例如,当有效触发查询时?)

这个问题的最佳解决方案是什么?

1 个答案:

答案 0 :(得分:4)

1)How to get First and Last record from a sql query?这是关于如何在一个查询中获取第一个和最后一个记录。

2)Here是sqlalchemy查询的文档。特别要注意union_all(从上面实施答案)。 它还有关于何时触发查询的信息(基本上,当您使用方法时会触发查询,返回结果,如first()all()。这意味着,Valuation.query.filter_by(..).order_by(sqlalchemy.desc(Valuation.date))将不会向数据库)。

另外,如果内存不是问题,我会说你的第一个查询得到all()个对象,只是通过python得到第一个和最后一个结果:

results = Valuation.query.filter_by(..).order_by(sqlalchemy.desc(Valuation.date)).all()
first_valuation = results[0]
last_valuation = results[-1]

它比执行两个(甚至是统一的)查询更快,但如果你的数据库足够大,可能会占用大量内存。

相关问题