'how do i get the highiest occured user in a table in Django
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```
Solution 1:[1]
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')[:0]
Solution 2:[2]
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
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | |
| Solution 2 | Richie |
