I would like to have the row number as a column of my queries. Since I am using MySql, I cannot use the built-in func.row_number()
of SqlAlchemy. The result of this query is going to be paginated, therefore I would like to keep the row number before the split happen.
session.query(MyModel.id, MyModel.date, "row_number")
I tried to use an hybrid_property
to increment a static variable inside MyModel
class that I reset before my query, but it didn't work.
@hybrid_property
def row_number(self):
cls = self.__class__
cls.row_index = cls.row_index + 1
return literal(self.row_index)
@row_number.expression
def row_number(cls):
cls.row_index = cls.row_index + 1
return literal(cls.row_index)
I also tried to mix a subquery with this solution :
session.query(myquery.subquery(), literal("@rownum := @rownum + 1 AS row_number"))
But I didn't find a way to make a textual join for (SELECT @rownum := 0) r
.
Any suggestions?
EDIT
For the moment, I am looping on the results of the paginated query and I am assigning the calculated number from the current page to each row.