1

Lets say I am modeling a VCS with Django, using a model something like this:

class VCSItem(models.Model):
    directory = models.CharField()
    name = models.CharField()
    revision = models.IntegerField()

Now (directory, name) uniquely identify an item tracked by my system, but each item may have multiple revisions.

I'd like to list all the items, where each item has the maximium tracked revision for my system. Does Django have in-built functionality for this?

Worst case, I could do it on my own with something like:

newest_items = {}
for item in VCSItem.objects.all().order_by("revision"):
    newest_item[item.directory + item.name] = item

The downside is that I have to fetch all entries from the database and loop over each -- something I'd rather avoid if possible.

ftartaggia
  • 541
  • 2
  • 11
Willi Ballenthin
  • 6,444
  • 6
  • 38
  • 52

1 Answers1

1

have a look at annotations and Max aggregation function: https://docs.djangoproject.com/en/dev/ref/models/querysets/#annotate https://docs.djangoproject.com/en/dev/ref/models/querysets/#max

VCSItem.objects.values('directory', 'name').annotate(max_rev=Max('revision'))
ftartaggia
  • 541
  • 2
  • 11
  • This approach does not return the full object, but a Dict containing `directory`, `name`, and `max_rev`. Is there a slick way to fetch the entire object? – Willi Ballenthin Sep 19 '11 at 15:05