Skip to content
Advertisement

How to get the most liked users in django rest-api

So I have a social media app, where users can like the posts of other users. Now I want to fetch the top 20 users who have received the most number of likes. I am pretty much confused how to query my Likes Model

My LIKES MODEL

JavaScript

SIMPLIFIED POST MODEL

JavaScript

SIMPLIFIED USER MODEL

JavaScript

** My View **

JavaScript

Advertisement

Answer

First I changed the user attribute in your Post model, I added related_name because otherwise the related names were clashing. This is the definition I used, otherwise your models are unchanged.

JavaScript

I.e. the posts by a user are accessible on User via the author attribute.

The following query gives you the top 20 users by number of likes they received:

JavaScript

Explanation:

  • Query User model and
  • annotate each user by doing a count:
    • author leads to the posts by the user
    • likes follows to PostLike and counts all likes which are associated with a post by the user
  • then order by number of likes descending,
  • and limit the number of retrieved objects to 20.
User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement