开发者

How to get latest of many groups at once

开发者 https://www.devze.com 2023-02-18 08:20 出处:网络
I have a model like this: class Foo(models.Model): date = models.DateTimeField() language = models.TextField()

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.开发者_JAVA技巧 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.


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.


Try this:

Foo.objects.values('language').annotate(max_date=Max('date')).order_by()

Or do you actually need the ID of records with max date?

You might want to read this: http://docs.djangoproject.com/en/dev/topics/db/aggregation/

0

精彩评论

暂无评论...
验证码 换一张
取 消