【发布时间】:2015-11-07 00:26:12
【问题描述】:
我有一个基于 Django 的网络应用程序,用户可以在其中聚集在一起聊天。我刚刚完成了一个功能,用户可以围绕任何感兴趣的主题创建自己的“聊天组”。这些可以是私有的,也可以是公开的可见的。
我的下一个挑战是显示所有现有公共群组的列表,按最热门的群组优先进行分页和排序。经过深思熟虑后,我决定最活跃的组是在过去 60 分钟内看到最多独特访问者(沉默或其他方式)的组。可以肯定的是,我所说的唯一性是指不同的用户,而不是同一个用户一次又一次地访问一个组。
在我的基于类的视图的get_queryset() 方法中获得所需的有序查询集的最有效方法是什么?其次,最有效的方法是在同一查询集中为每个组对象添加 total distinct views 注释,以便我可以额外显示 total观看次数,同时根据当前热门进行排序?
相关模型有:
class Group(models.Model):
topic = models.TextField(validators=[MaxLengthValidator(200)], null=True)
owner = models.ForeignKey(User)
private = models.CharField(max_length=50, default=0)
created_at = models.DateTimeField(auto_now_add=True)
class GroupTraffic(models.Model):
visitor = models.ForeignKey(User)
which_group = models.ForeignKey(Group)
time = models.DateTimeField(auto_now_add=True)
相关观点是:
class GroupListView(ListView):
model = Group
form_class = GroupListForm
template_name = "group_list.html"
paginate_by = 25
def get_queryset(self):
return Group.objects.filter(private=0,date__gte=???).distinct('grouptraffic__visitor').annotate(recent_views=Count('grouptraffic__???')).order_by('-recent_views').annotate(total_views=Count('grouptraffic__which_group=group'))
如您所见,我在上面的get_queryset(self) 方法中非常挣扎,注释了两次,什么都没有。请指教!
【问题讨论】:
标签: python django performance django-views django-queryset