Home > front end >  Get Highest Likes User with Django
Get Highest Likes User with Django

Time:08-03

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

CodePudding user response:

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

from django.db.models import Count

profiles = Profile.objects.annotate(total_likes=Count('likes')).order_by('total_likes')
  • Related