所以我想尝试列出最受欢迎的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 :\
我真的很感激对此有所了解。我正在做的不行。如何查询热门事件?
答案 0 :(得分:8)
使用annotations:
from django.db.models import Count
popular_events = Events.objects.annotate(attendee_count=Count('attendee')).filter(attendee_count__gt=50)