用django-voting投票排序的问题

时间:2009-02-13 03:25:23

标签: python django django-voting

我有一个模型Post和一个模型投票。投票(表单django-voting)基本上只是一个指向帖子和-1,0或1的指针。

还有Tourn,这是一个开始日期和结束日期。在Tourn开始和结束之间发布的帖子将提交给该锦标赛。

为了进行代表计算,我试图找到锦标赛的前三名获胜者。这就是我所拥有的:

    posts = Post.objects.filter(status=2, created_at__range=(tourn.start_date, tourn.end_date))

    start = tourn.start_date - timedelta(days=1)
    end = tourn.end_date + timedelta(days=1)
    qn = connection.ops.quote_name
    ctype = ContentType.objects.get_for_model(Post)

    posts.extra(select={'score': """
            SELECT SUM(vote)
            FROM %s
            WHERE content_type_id = %s
            AND object_id = %s.id
            AND voted_at > DATE(%s)
            AND voted_at < DATE(%s)
        """ % (qn(Vote._meta.db_table), ctype.id, qn(Post._meta.db_table), start, end)},
                order_by=['-score'])

    if tourn.limit_to_category:
        posts.filter(category=tourn.category)

    if len(posts) >= 1:
        tourn_winners_1.append(posts[0].author)
        resp += " 1: " + posts[0].author.username + "\n"

    if len(posts) >= 2:
        tourn_winners_2.append(posts[1].author)
        resp += " 2: " + posts[1].author.username + "\n"

    if len(posts) >= 3:
        tourn_winners_3.append(posts[2].author)
        resp += " 3: " + posts[2].author.username + "\n"

这似乎很简单,但由于某种原因,结果是错误的。

因此得出的查询是:

SELECT "blog_post"."id", "blog_post"."title", "blog_post"."slug", "blog_post"."a
uthor_id", "blog_post"."creator_ip", "blog_post"."body", "blog_post"."tease", "b
log_post"."status", "blog_post"."allow_comments", "blog_post"."publish", "blog_p
ost"."created_at", "blog_post"."updated_at", "blog_post"."markup", "blog_post"."
tags", "blog_post"."category_id" FROM "blog_post" WHERE ("blog_post"."status" =
2  AND "blog_post"."created_at" BETWEEN 2008-12-21 00:00:00 and 2009-01-04 00:00
:00) ORDER BY "blog_post"."publish" DESC

似乎posts.extra()根本没有应用于查询...

1 个答案:

答案 0 :(得分:3)

我认为您需要将posts分配给posts.extra()的返回值:

posts = posts.extra(select={'score': """
                    SELECT SUM(vote)
                    FROM %s
                    WHERE content_type_id = %s
                    AND object_id = %s.id
                    AND voted_at > DATE(%s)
                    AND voted_at < DATE(%s)
                """ % (qn(Vote._meta.db_table), ctype.id, qn(Post._meta.db_table), start, end)},
                        order_by=['-score'])