I have the following Django (3.0) ORM model:
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)
I want to group them by the code
field and for each code only take the portfolio that has the max date
I know I can use the following query:
Portfolio.objects.values('code').annotate(latest=Max('date'))
But it has three problems:
- It gives me only the
code
andlatest
fields, so I lose the other fields - It gives back a dictionary, while I want a list of actual
Portfolio
objects Max
works becausedate
is aDateField
. 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 instancename
and take the first record for each group?
So, to sum up, my question: 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?