2013-03-21 85 views
1

考虑用下面的DB行的模式:Django的GROUP BY查询

| Kind | Age(days) | Color | 
------------------------------- 
| Apple | 1  | Red | 
| Apple | 2  | Red | 
| Apple | 3  | Red | 
| Apple | 1  | Green | 
| Apple | 2  | Green | 
| Plum | 1  | Purple | 
| Plum | 2  | Purple | 
| Cherry | 1  | Red | 
| Cherry | 2  | Red | 

我想选择每种颜色的一个最古老的水果,所以我应该结束了:

| Kind | Age(days) | Color | 
------------------------------- 
| Apple | 3  | Red | 
| Apple | 2  | Green | 
| Plum | 2  | Purple | 

我知道,在SQL它看起来是这样的:

SELECT * FROM `fruit` GROUP BY `color` ORDER BY `age` DESC; 

这是如何使用的Django的QuerySet API做了什么?我所看到的有关聚合的大部分内容涉及计算事物,但我希望返回实际的对象,而不是对它们进行计数。

+0

您正在寻找这样的:[Django的聚集(http://stackoverflow.com/questions/629551/how-to-query-as-group-by-in-django) – PepperoniPizza 2013-03-21 23:19:13

+0

@PepperoniPizza:我检查了您引用的问题并再次查看了文档,但仍未找到使用聚合的方法来完成此操作。谨慎阐述? – visum 2013-03-22 22:38:44

回答

0
def myview(request):  
    lists = [] 
    colors = Fruit.objects.values_list('color', flat=True).distinct() 
    for color in colors: 
     fruits = Fruit.objects.filter(color=color).order_by('-age')[:1] 
     for fruit in fruits: 
      lists.append({'kind': fruit.kind, 'age': fruit.age, 'color': fruit.color}) 
    return render(request, 'page.html', {'fruits': lists}) 
+0

这不是我希望的解决方案,但缺乏一个更清洁的方法,这基本上是我最终做的。 – visum 2013-03-25 15:13:34