Django方法限制分组查询

时间:2013-06-25 16:14:17

标签: sql django postgresql django-orm

我想为每个日期返回3个结果,并按日期和每个查询的单独“评级”列排序结果

例如,我的查询将返回如下内容:

Event on Dec 1st rated 36
Event on Dec 1st rated 29
Event on Dec 1st rated 12
Event on Dec 2nd rated 45
Event on Dec 2nd rated 12
Event on Dec 2nd rated 9
Event on Dec 3rd rated 118
Event on Dec 3rd rated 15
Event on Dec 3rd rated 13

我知道这应该可以使用原始sql,如下所示:SQL group - limit

但我想知道是否有一种方法可以在单个查询中在Django ORM中执行此操作,或者至少有一种方法可以使其尽可能轻松,如果我确实需要转换为原始SQL查询。

修改 模型很简单。相关领域是:

class Event(models.Model):
  title = models.CharField(max_length=120)
  day = models.DateField()
  score = models.SmallIntegerField()

1 个答案:

答案 0 :(得分:1)

我试图组建一个查询集联盟,但是django抱怨道:

AssertionError
Cannot combine queries once a slice has been taken.

这是观看代码:

def home2(request):

    dates_qs = Event.objects.values('day').order_by('day').distinct()

    ev_qss = []
    for date in dates_qs:
        my_qs = Event.objects.filter(day=date['day']).order_by('score')[:3]
        ev_qss.append(my_qs)

    answer_qs = ev_qss[0]
    for qs in ev_qss[1:]:
        answer_qs |= qs

    return render_to_response ('home2.html',
                               {'dates_qs':dates_qs,
                                'answer_qs':answer_qs},
                               RequestContext(request))

为行answer_qs |= qs发出错误,即想要获取answer_qs和qs的并集。 qs是日期分数的查询集,限制为3个结果。

所以我猜你会被原始SQL困住。您指向的原始SQL示例包含多个表中的数据,并且您将所有数据放在一个表中,因此您的SQL更简单:

SELECT sE.* FROM so_event AS sE
WHERE 3>(
         SELECT COUNT(*)
         FROM so_event iE
         WHERE iE.day = sE.day AND
         sE.score - iE.score < 0
)
ORDER BY sE.day ASC, sE.score DESC;

现在我知道这是我们的目标,我搜索了django orm子查询,并且遇到了这篇SO文章并回答:

How to django ORM with a subquery?

其中说了很多东西,并暗示你可以用不同的ORM(SQLAlchemy)做你想做的事。我听说过关于SQLAlchemy的好消息。