user8557845
user8557845

Reputation:

Django: Querying the Database

Here's my model,

class Question(models.Model):
    user = models.ForeignKey(User)
    followers = models.ManyToManyField(User, related_name='user_follow')

I was wondering, how can I filter out the 3 most followed questions by the Users?

Thank You :)

Upvotes: 0

Views: 43

Answers (2)

Juho Enala
Juho Enala

Reputation: 69

You could order queryset by follower count. Like this:

from django.db.models import Count

most_followed = Question.objects.annotate(follower_count=Count('user_follow')).order_by('-follower_count')

To filter out 3 most followed questions:

top_three = most_followed[:3]

Upvotes: 1

user8060120
user8060120

Reputation:

Can you try it:

from django.db.models import Count

Question.objects.annotate(cnt_f=Count('followers')).order_by('user', '-cnt_f')[:3]

more details in the doc

Upvotes: 1

Related Questions