4

所以我试图通过每个中有events多少来获得最受欢迎的列表。attendees'event'

楷模

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')

意见

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 :\

我真的很感激对此的一些见解。我在做什么是行不通的。如何查询热门活动?

4

1 回答 1

9

使用注释

from django.db.models import Count

popular_events = Events.objects.annotate(attendee_count=Count('attendee')).filter(attendee_count__gt=50)
于 2012-06-20T20:18:32.740 回答