Django使用聚合MAX

时间:2015-07-27 13:38:10

标签: python django django-models

我有以下......

r = Region.objects.get_location_name(user.location)

返回:

[<Region: Great Britain>, <Region: Europe>]

接下来我想只返回MAX最高parent的对象。

我试过这个:

r = Region.objects.get_location_name(user.location).aggregate(Max('level'))

但这不会返回它返回的对象......

{'level__max': 1}

为什么?

1 个答案:

答案 0 :(得分:1)

您正在寻找order_by:通过降级&#39;对查询集进行排序&#39;然后通过queryset[0]获得第一项。

认为您的代码应该看起来像

r = Region.objects.get_location_name(user.location).order_by('-level')[0]