Django equivalent for latest entry for each user

Posted by paul-ogrady on Stack Overflow See other posts from Stack Overflow or by paul-ogrady
Published on 2010-04-05T10:43:06Z Indexed on 2010/04/05 10:53 UTC
Read the original article Hit count: 384

Filed under:

Hi,

I'm surprised this question hasn't come up. Couldn't find much on the web.

Using Entry.objects.latest('created_at') I can recover the latest entry for all Entry objects, but say if I want the latest entry for each user? This is something similar to an SQL latest record query. But how do I achieve this using the ORM? Here is my approach I'm wondering if it is the most efficient way to do what I want.

First I perform a sub query: Objects are grouped by user and the Max (latest) created_by field is returned for each user (created_at__max) I then filter Entry objects based on the results in the subquery and get the required objects.

Entry.objects.filter(created_at__in=Entry.objects.values('user').annotate(Max('created_at')).values_list('created_at__max'))

or using a manager:

class UsersLatest(models.Manager):  

    def get_query_set(self):
        return Super(UsersLatest,self).get_query_set().filter(created_at__in=self.model.objects.values('user').annotate(Max('created_at')).values_list('created_at__max'))

Is there a more efficient way? possibly without sub query?

Thanks,

Paul

© Stack Overflow or respective owner

Related posts about django