DJANGO : How to filter the last data collected for each type of object in a model?

Viewed 122

Let's say I have this model

class TreeCensus(models.Model):

    name            = models.CharField() #Oak, elm, ...
    identified_at   = models.DateTimeField(auto_now_add=True)

I want to get a QS with the last Census of each tree.

I tried naively this

TreeCensus.object.order_by('name').last()

But It obviously returned me the last of all the TreeCensus objects.

So what is the best way (or at least a good one) to do this? For example if there are 2 Oak in the QS I want to get the first one filtered

1 Answers

You can .annotate(…) [Django-doc] with:

from django.db.models import Max

TreeCensus.objects.values('name').annotate(
    last_seen=Max('identified_at')
).order_by('name')

This will produce a QuerySet of dictionaries with name and last_seen as keys where last_seen will contain the largest (latest) timestamp for that name.

Related