please I need help with this, am building an app that allows users to send out invites, and I want to get the user with the highest sent out invitations, how do I go about it. my model is as below.
class Invite(models.Model):
host_name = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.SET_NULL)
invite = models.CharField(max_length=200, null=True,blank=True)
def __str__(self):
return self.name```
CodePudding user response:
All you need to do is import Count. Count the host_name of Invite() objects. And after get the only one host_name by ordering from reverse
Have Fun!
from django.db import Count
Invite.objects.annotate(num_likes=Count('host_name')).filter(host_name__gt=).order_by('-host_name')[:1]
CodePudding user response:
here is the modification of Enes solution that worked for me
user_with_highest_sent_out_invite = User.objects.annotate(num_of_invites=Count('invite__host_name')).order_by('-num_of_invites')[0]
however when there is a tie, it fetches the first object as specified above