15
Using Entry.objects.latest('created_at') I can recover the latest Entry for all Entry objects. But how do I get the latest Entry for each user? This is something similar to an SQL latest-record query. How do I achieve this using the ORM? Here's my approach, and 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 a subquery?