Here is what I use to extract next / prev from an object using sqlalchemy. The idea is to get the row_number of the object from the source list and execute another query with offset +/- 1.
I use a subquery with ROW_NUMBER ( How to use ROW_NUMBER ()? ) To retrieve row_number from the original query:
row_number = func.row_number().over(order_by=orders).label("row_number") row_number_subquery = self.getlistquery(columns=chain([row_number], pk_columns)).subquery()
Then I join the model on primary keys:
join_clause = [getattr(row_number_query.c, pk.key) == getattr(model, pk.key) for pk in pk_columns]
I filter the main keys of the object:
filter = [getattr(model, pk.key) == pk_values[index] for index, pk in enumerate(pk_columns)]
I create a final query to get the offset of the object:
offset = db.session.query(row_number_subquery).join(model, *join_clause).filter(*filter).first()
Then the element contains the offset needed for the next or offset-2 for the previous one (starting from 1 for row_number and 0 for offset)
self.getlistquery().offset(offset)
gdoumenc
source share