biancang
biancang

Reputation: 63

Get second row from a SQLAlchemy query

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)

Upvotes: 1

Views: 3296

Answers (3)

Arkcann
Arkcann

Reputation: 668

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.

Upvotes: 2

xie Faiz
xie Faiz

Reputation: 59

after limit function, use index to find it

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

Upvotes: 3

Wuuzzaa
Wuuzzaa

Reputation: 56

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

Upvotes: 0

Related Questions