I have a model like this:
class Foo(models.Model):
date = models.DateTimeField()
language = models.TextField()
# other stuff
And I want to group the Foo
s 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.
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 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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With