title: django annotate a function that returns the maximum of a field among all objects that has a feature
body: <p>Suppose that I have this model:</p>
  
  <pre><code>class Student(models.Model):
      class_name = models.CharField()
      mark = models.IntegerField()
  </code></pre>
  
  <p>And I want to get all the students that have the highest <code>mark</code> in their class. I can get the student who has the highest <code>mark</code> in all the classes like it is mentioned in <a href="https://stackoverflow.com/questions/9838264/django-record-with-max-element">this post</a>. But I want all the students that have the highest <code>mark</code> <strong>in their class</strong>, something like this:</p>
  
  <pre><code>Student.objects.annotate(
      highest_mark_in_class=Max(
          Students.objects.filter(class_name=F('class_name'))
          .filter(mark=highest_mark_in_class)
      )
  )
  </code></pre>
  
  <p>I can do this with a <code>for</code> loop, but with a large database <code>for</code> loops are rather slow. I don't know if it's possible to write such a query in one line?</p>