Get second row from a SQLAlchemy query

Question:

I can get the first value using myQuery.first(), but I want to get the second row/value. How can I do that?

myQuery = db.session.query(Inquiry).order_by(func.count(Ruling.id).desc()).limit(2)
Asked By: biancang

||

Answers:

Try to use myQuery[1] to get the second row. After you used your query.

Answered By: Wuuzzaa

after limit function, use index to find it

myQuery = db.session.query(Inquiry).order_by(func.count(Ruling.id).desc()).limit(2)[1]
Answered By: xie Faiz

This can be accomplished by applying offset to the returned query, and then getting the first() result:

db.session.query(Inquiry).order_by(func.count(Ruling.id).desc()).offset(1).first()

This has the advantage that it doesn’t raise an exception if there are no results – though, you could use one() if you did want an exception in this case.

Edit: I also found that if you need to handle the case where there may not be a previous row, and you want to fallback to the first row, you can do:

db.session.query(Inquiry).order_by(func.count(Ruling.id).desc()).limit(2)[-1]

The [-1] in this case gets you the last element in the list – so if the query returns 2 elements, you get the second element. But if it only returns 1 element, you get that one. Though this would raise an index out of range exception if no elements are returned.

Answered By: Arkcann
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.