Using func ranking in SQLAlchemy to rank rows in a table

I have a table defined like this:

 Column    |  Type   | Modifiers | Storage | Stats target | Description
-------------+---------+-----------+---------+--------------+-------------
 id          | uuid    | not null  | plain   |              |
 user_id     | uuid    |           | plain   |              |
 area_id     | integer |           | plain   |              |
 vote_amount | integer |           | plain   |              |

I want to be able to generate a rank column when I query this database. This rank column will be ordered by column vote_amount. I tried to create a query for this, it looks like this:

subq_rank = db.session.query(user_stories).add_columns(db.func.rank.over(partition_by=user_stories.user_id, order_by=user_stories.vote_amount).label('rank')).subquery('slr')
data = db.session.query(user_stories).select_entity_from(subq_rank).filter(user_stories.area_id == id).group_by(-subq_rank.c.rank).limit(50).all()

I hope my attempt will give you an idea of ​​what I'm trying to achieve.

Thank.

+4
source share

All Articles