1

次の DB 行を持つモデルがあるとします。

| 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    |

各色の最も古い果物を 1 つ選択したいので、最終的には次のようになります。

| 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 に答える