Get Highest Likes User with Django

Question:

class Profile(models.Model):
    ..
    goldcoin = models.IntegerField(default=0)

    likes = models.ManyToManyField(User, blank=True, related_name='user_like')
    dislikes = models.ManyToManyField(User, blank=True, related_name='user_dislike')

    def __str__(self):
        return self.user.username
    
    def get_avatar(self):
        ..

from likes = models.ManyToManyField(User, blank=True, related_name='user_like') How to get Highest Likes User?

Example i have user like this

  • User Likes
  • Jhon 30
  • Aish 25
  • Josh 5
  • Adam 50

Output

  • User Likes
  • Adam 50
  • Jhon 30
  • Aish 25
  • Josh 5

Django 4.0.6
Python 3.10.2

Asked By: Smile Pumpkin

||

Answers:

You can aggregate a total number of likes using Count, then order the queryset by total number of likes

from django.db.models import Count

profiles = Profile.objects.annotate(total_likes=Count('likes')).order_by('total_likes')
Answered By: Ersain
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.