Consider a simple model:
考虑一个简单的模型:
class Person(models.Model):
name = models.CharField(max_length=256)
age = models.IntegerField()
I would like a single expression which returns a QuerySet
of all of the Person
objects whose age is maximal in the table. I.e. say there are 20 Person
records, and the largest age is 70
but there are 3 distinct records which have that value. I would like my queryset to contain exactly those 3 Person
objects.
我希望有一个表达式,它返回表中年龄最大的所有Person对象的QuerySet。也就是说,有20个人的记录,最大的年龄是70岁,但是有3个不同的记录有这个价值。我希望我的queryset恰好包含这3个Person对象。
I suppose I could do:
我想我可以:
Person.objects.filter(age=Person.objects.aggregate(models.Max('age'))['age__max'])
But wow that seems like a real mess. And it hits the database twice. Yuck.
但哇,这看起来真是一团糟。它会访问数据库两次。讨厌的东西。
Better alternatives?
其它更好的选择吗?
1 个解决方案
#1
1
I can't directly answer your question, but I feel like you shouldn't beat up for getting this in one query, making your code clear is also important. So why don't you do:
我不能直接回答您的问题,但是我觉得您不应该因为在一个查询中获得这个而感到紧张,使您的代码清晰也是很重要的。所以你为什么不这样做呢:
from django.db.models import Max
# assumes that you have at least one record
max_age = Person.objects.aggregate(Max('age'))['age__max']
oldest_folks = Person.objects.filter(age=max_age)
Max
would do MAX
in sql statement, filter
would do a simple sql lookup, none of the operations are awfully expensive.
Max会做Max in sql语句,filter会做一个简单的sql查找,所有的操作都不会太贵。
#1
1
I can't directly answer your question, but I feel like you shouldn't beat up for getting this in one query, making your code clear is also important. So why don't you do:
我不能直接回答您的问题,但是我觉得您不应该因为在一个查询中获得这个而感到紧张,使您的代码清晰也是很重要的。所以你为什么不这样做呢:
from django.db.models import Max
# assumes that you have at least one record
max_age = Person.objects.aggregate(Max('age'))['age__max']
oldest_folks = Person.objects.filter(age=max_age)
Max
would do MAX
in sql statement, filter
would do a simple sql lookup, none of the operations are awfully expensive.
Max会做Max in sql语句,filter会做一个简单的sql查找,所有的操作都不会太贵。