1

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

| 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 完成的?我看到的关于聚合的大部分内容都涉及计数,但我希望返回实际对象,而不是计数。

4

1 回答 1

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})
于 2013-03-22T02:25:13.247 回答