Modelesq
Modelesq

Reputation: 5402

Get 'most popular' list in Django

So I'm trying to get the a list of the most popular events by how many attendees are in each 'event'.

Models

class Event(models.Model):
    heading = models.CharField(max_length=200)
    sub_heading = models.CharField(max_length=200, null=True, blank=True)
    url = models.CharField(max_length=200, null=True, blank=True)
    description = models.TextField()
    tags = models.ManyToManyField(Tag, null=True, blank=True)
    date = models.DateTimeField()
    created = models.DateTimeField(auto_now_add=True)
    modified = models.DateTimeField(auto_now=True)

    def attendees(self):
        return Attendee.objects.filter(event=self)

class Attendee(models.Model):
    event = models.ForeignKey(Event)
    content_type = models.ForeignKey(ContentType, related_name='event_attendee')
    object_id = models.PositiveIntegerField()
    profile = generic.GenericForeignKey('content_type', 'object_id')

Views

def event(request, id):
    ...
    events = Events.objects.all()
    attendees = Attendee.objects.filter(event__in=events).count()
    if attendees > 50:
        popular_events = Event.objects.filter(what should i filter by).annotate(attendees_count=Count('attendees')).order_by('-attendee_count') ???
   # I'm probably going about this the wrong way :\

I'd really appreciate some insight into this. What I'm doing isn't working. How to I get a query of popular events?

Upvotes: 5

Views: 3415

Answers (1)

Chris Pratt
Chris Pratt

Reputation: 239290

Use annotations:

from django.db.models import Count

popular_events = Events.objects.annotate(attendee_count=Count('attendee')).filter(attendee_count__gt=50)

Upvotes: 10

Related Questions