python - 在 Django 中获取 'most popular' 列表

标签 python django

因此,我试图通过每个 “事件” 中有多少 attendee 来获取最受欢迎的 events 列表。

模型

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

我真的很感激能对此有所了解。我在做什么是行不通的。如何查询热门事件?

最佳答案

使用annotations :

from django.db.models import Count

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

关于python - 在 Django 中获取 'most popular' 列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11127448/

相关文章:

python - 如何在我自己的 View 中使用 Django 管理列表和过滤?

python - 以带有分隔符的字符串形式返回列表

python - 参数默认使用python中的其他参数

python - 向量化形式以获取大于引用的元素数

python - 从 Django 中的一种形式创建对象的多个实例

php - 使用 PHP 或 Django 在 Apache 中重定向八位字节流

python - Python 中有两个条件的 if 语句

python - 如何根据列值对 Pandas 数据框进行切片?

python - 具有多种方法的基于类的 View 如何与 django 中的 url 一起使用?

python - 如何在django中传递绝对url