Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get latest 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 the Foos by language, then get the latest one in each group. I haven't been able to figure out how to use django's QuerySet API to do this (honestly, I don't know how to do it in SQL either). So 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 resembling this result:

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

Where perhaps instead of numbers those are complete Foo objects.

like image 846
luqui Avatar asked Mar 23 '11 02:03

luqui


People also ask

How do you GROUP BY and get the latest record in SQL?

Retrieving the last record in each group using GROUP BY There are two solutions explained here using the GROUP BY clause. In both these solutions, we will be using the MAX() function to get the maximum value of id and then retrieving the other columns corresponding to this maximum id.

How do you find the latest record by GROUP BY?

How to Select Most Recent Record for Each User. First, we get the latest date for each user id using GROUP BY. Now that we know the most recent date for each user id, we join this result with our original table to get the latest record by user group.

How do I get the latest record for each ID in MySQL?

If hypothetically MySQL had a last() function which returned values from the last row in a special ORDER BY clause then we could simply do: SELECT last(t1.id) AS id, t1. groupID, last(t1. recordedTimestamp) AS recordedTimestamp, last(t1.


1 Answers

You can use a raw query 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'm using SQLite syntax, but other SQL languages should be similar.

like image 96
Danilo Freitas Avatar answered Sep 30 '22 17:09

Danilo Freitas