Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Get Highest Likes User with Django

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

Django 4.0.6
Python 3.10.2

>Solution :

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')
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading