0

This answer tells you how to get the last row from a session query:

obj = session.query(ObjectRes).order_by(ObjectRes.id.desc()).first()

I need the one before it - how do you get the second last one?

Ilja Everilä
  • 50,538
  • 7
  • 126
  • 127
cardamom
  • 6,873
  • 11
  • 48
  • 102
  • 1
    get all (or with `LIMIT 2`) and use `obj[1]`. Or use `OFFSET 1` in SQL query – furas Jul 29 '19 at 15:26
  • Will this work? obj = session.query(ObjectRes).order_by(ObjectRes.id.desc())[-2] – Amit Jul 29 '19 at 15:29
  • @Amit no, that thing is not a list, it's a `` – cardamom Jul 29 '19 at 15:33
  • you should already use Google to check `LIMIT` and `OFFSET` in sqlalchemy – furas Jul 29 '19 at 16:05
  • if you use `first()` to get last row then using `[-2]` you would get `second-first`, not `second-last`. You would have to change `order_by` to get it in different order and then use `.fetchall()[-2]`. Or keep order_by and use `[1]` – furas Jul 29 '19 at 16:10

1 Answers1

3
obj = session.query(ObjectRes).order_by(ObjectRes.id.desc()).offset(1).first()
everfight
  • 420
  • 3
  • 10