Django Query number list and return selected rows

I am creating scoreboard view for button counts. The model is simply user id and count. API must return "id", "count" and "position" on leaderboard. If no id provided, it simply returns top three. But if there is id, aditionaly to top three, I must provide the position of id on leaderboard.

The problem is, when I use Window( RowNumber() ), and then attempt to select by id, the whole query runs on that one selected item. So the "position" is always 1.

I found dirty solution to practically take raw query after Window, and then selecting by id. In that case, proper "position" remains. But I feel there is a better way to do it.

I would really appreciate any suggestions

Using:

sql, params = queryset.query.sql_with_params()
queryset = queryset.raw(f"SELECT ...", params)
Back to Top