这个问题已经被问过多次,但我无法让我的代码工作。无论如何,假设我有一个博客,其中包含博客文章:
class BlogPost(models.Model): # This class doesn't really matter
author = models.ForeignKey(myUser)
text = models.TextField()
碰巧我使用另一个模型记录了每篇博客文章的访问:
class Activity(models.Model):
user_id = models.CharField()
# I log different types of activities, hence the choice
action_id = models.IntegerField(choices=ACTIVITY_ACTIONS)
object_id = models.CharField()
created_at = models.DateTimeField()
我想要的是获得自精确日期以来访问次数最多的博客文章,按浏览次数排序。我现在在做什么(在活动管理器中):
def get_blogposts_most_viewed_since(self, date):
# I get all related activities (blog posts views since date)
activities = Activity.objects.since(date).filter(action_id=BLOGPOST_VIEW)
# I get all blogposts' ids
blogpost_ids = events.values('object_id')
# I get all blogposts ordered by their number of views:
blogposts = BlogPost.objects.filter(id__in=blogpost_ids)\
.annotate(nb_views=Count('id')).order_by('-nb_views')
return blogposts
这行不通。我做了一些测试:我创建了三篇博客文章,blogpost_a 被查看了两次,blogpost_b 被查看了一次,而 blogpost_c 没有得到任何查看。当我打电话时,get_blogposts_most_viewed_since
我确实得到了 blogpost_a 和 blogpost_b,但似乎是随机顺序。
我尝试使用以下方法进行一些调试:
for blogpost in blogposts:
print blogpost.nb_views
两篇博文(a 和 b)都有nb_views == 1
.
我究竟做错了什么?