Is there any way to get the prev/next records from a SqlAlchemy query? Like so:
record.id
record.next.id
record.prev.id
I could add the prev/next methods to each model myself, but I’m wondering if there is already some automagical way that I overlooked. The web application in question is written in Pylons.
Edit:
This is probably a dirty hack, but it works. I imported the sqlalchemy Session object into my model and did this:
def next(self):
return Session.query(Blog).filter(Blog.id > self.id).order_by(Blog.id).first()
def prev(self):
return Session.query(Blog).filter(Blog.id < self.id).order_by(desc(Blog.id)).first()
What I would suggest doing is in your original query requesting -1 and +1 so that you can easily get the ID’s without having to run another query saving time on processing on the SQL server.
Your solution definitely works, but requires an extra two queries. You could even make it a subquery so that if you just want to retrieve a single row and throw previous/next on it that data is stored in a column created by a sub-query.