Suppose that I have this model:
class Student(models.Model):
class_name = models.CharField()
mark = models.IntegerField()
And I want to get all the students that have the highest mark
in their class. I can get the student who has the highest mark
in all the classes like it is mentioned in this post. But I want all the students that have the highest mark
in their class, something like this:
Student.objects.annotate(
highest_mark_in_class=Max(
Students.objects.filter(class_name=F('class_name'))
.filter(mark=highest_mark_in_class)
)
)
I can do this with a for
loop, but with a large database for
loops are rather slow. I don't know if it's possible to write such a query in one line?