Django equivalent for latest entry for each user
- by paul-ogrady
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