title: Django, group by one field, only take the latest / max of each group and get back the ORM objects
body: <p>I have the following Django (3.0) ORM model:</p>
  
  <pre><code>class Portfolio(models.Model):
      code = models.CharField(max_length=20)
      name = models.CharField(max_length=100)
      date = models.DateField()
      created = models.DateTimeField(blank=True, null=True, auto_now_add=True)
  </code></pre>
  
  <p>I want to group them by the <code>code</code> field and for each code only take the portfolio that has the max <code>date</code></p>
  
  <p>I know I can use the following query:</p>
  
  <pre><code>Portfolio.objects.values('code').annotate(latest=Max('date'))
  </code></pre>
  
  <p>But it has three problems:</p>
  
  <ol>
  <li>It gives me only the <code>code</code> and <code>latest</code> fields, so I lose the other fields</li>
  <li>It gives back a dictionary, while I want a list of actual <code>Portfolio</code> objects</li>
  <li><code>Max</code> works because <code>date</code> is a <code>DateField</code>. It would also work on other numeric field types, but what if I want to order the records by the value of a CharField (lexicographic order), for instance <code>name</code> and take the first record for each group?</li>
  </ol>
  
  <p>So, to sum up, my question: <strong>How do I use Django ORM to retrieve a list of ORM Objects grouped by one or more fields and have back only the first record of each group given an arbitrary "order by" clause?</strong></p>