按出现次数对模型进行排序

时间:2013-07-18 08:25:27

标签: django orm count

这个问题已被多次询问,但我无法使我的代码生效。无论如何,假设我有一个博客,有博客文章:

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,但看起来像是一个random_order。

我尝试用以下方法进行调试:

for blogpost in blogposts:
    print blogpost.nb_views

两个博文(a和b)都有nb_views == 1

我做错了什么?

0 个答案:

没有答案