title: Django ORM: Getting rows based on max value of a column
body: <p>I have a class Marketorders which contains information about single market orders and they are gathered in snapshots of the market (represented by class Snapshot). Each order can appear in more than one snapshot with the latest row of course being the relevant one.</p>
  
  <pre><code>class Marketorders(models.Model):
      id = models.AutoField(primary_key=True)
      snapid = models.IntegerField()
      orderid = models.IntegerField()
      reportedtime = models.DateTimeField(null=True, blank=True)
      ...
  
  
  class Snapshot(models.Model):
      id = models.IntegerField(primary_key=True)
      ...
  </code></pre>
  
  <p>What I'm doing is getting all of the orders across several snapshots for processing, but I want to include only the most recent row for each order. In SQL I would simply do:</p>
  
  <pre><code>SELECT m1.* FROM marketorders m1 WHERE reportedtime = (SELECT max(reportedtime)  
  FROM marketorders m2 WHERE m2.orderid=m1.orderid);
  </code></pre>
  
  <p>or better yet with a join:</p>
  
  <pre><code>SELECT m1.* FROM marketorders m1 LEFT JOIN marketorders m2 ON 
  m1.orderid=m2.orderid AND m1.reportedtime &lt; m2.reportedtime 
  WHERE m2.orderid IS NULL;
  </code></pre>
  
  <p>However, I just can't figure out how to do this with Django ORM. Is there any way to accomplish this without raw SQL?</p>
  
  <p>EDIT: Just to clarify the problem. Let's say we have the following marketorders (leaving out everything unimportant and using only orderid, reportedtime):</p>
  
  <pre><code>1, 09:00:00
  1, 10:00:00
  1, 12:00:00
  2, 09:00:00
  2, 10:00:00
  </code></pre>
  
  <p>How do I get the following set with the ORM?</p>
  
  <pre><code>1, 12:00:00
  2, 10:00:00
  </code></pre>