Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get 'most popular' list in Django

Tags:

python

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?

like image 260
Modelesq Avatar asked Jan 16 '23 08:01

Modelesq


1 Answers

Use annotations:

from django.db.models import Count

popular_events = Events.objects.annotate(attendee_count=Count('attendee')).filter(attendee_count__gt=50)
like image 65
Chris Pratt Avatar answered Jan 18 '23 23:01

Chris Pratt