Django GROUP BY查询

时间:2013-03-21 22:11:01

标签: django

给定具有以下数据库行的模型:

| 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完成此操作?我看到的关于聚合的大部分内容涉及计算事物,但我想要实际的对象,而不是它们的数量。

1 个答案:

答案 0 :(得分: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})