from django.db.models import Max
# Find the maximum value of the rating and then get the record with that rating.
# Notice the double underscores in rating__max
max_rating = App.objects.aggregate(Max('rating'))['rating__max']
return App.objects.get(rating=max_rating)
这样可以保证有效地获得最大的元素之一,而不是对整个表排序并获得顶部(大约 O (n * logn))。
如果你想要一个随机的评论,也许可以改进@afahim 关于@Raydel Miranda 评论的回答。如果你想要全部,那么只用过滤器
from django.db.models import Max
# Find the maximum value of the rating and then get the record with that rating.
# Notice the double underscores in rating__max
max_rating = App.objects.aggregate(Max('rating'))['rating__max']
return App.objects.filter(rating=max_rating).first()
from django.db.models import Max, Value
from django.db.models.functions import Coalesce
max_rating = SomeModel.objects.aggregate(
max_rating=Coalesce(Max('rating'), Value(0))
)['max_rating']