How to get the last of many groups at once

I have a model like this:

class Foo(models.Model): date = models.DateTimeField() language = models.TextField() # other stuff 

And I want to group Foo by language, and then get the last in each group. I could not figure out how to use the django QuerySet API for this (to be honest, I don't know how to do this in SQL). For example:

 pk | date | language ---+--------+------------------ 1 | 1:00 | python 2 | 1:30 | python/django 3 | 1:45 | haskell 4 | 2:15 | python 5 | 2:45 | haskell 

I want to get something similar to this result:

 { 'python': 4, 'python/django': 2, 'haskell': 5 } 

Where, perhaps, instead of numbers, these are completed Foo objects.

+8
django django-queryset
source share
2 answers

You can use a raw request to solve your problems:

 query = Foo.objects.raw('SELECT id, language, MAX(date) FROM sqltest_foo GROUP BY language;') for foo in query: print foo.id, foo.language 

Obs: I use SQLite syntax, but other SQL languages ​​should be similar.

+2
source share

Try the following:

Foo.objects.values ​​('language'). Annotation (max_date = Max ('date')). Order_by ()

Or do you really need a post ID with a maximum date?

You can read the following: http://docs.djangoproject.com/en/dev/topics/db/aggregation/

0
source share

All Articles