0

Assume the following simplified models:

class Blog(models.Model):
    name = models.CharField()

class Author(models.Model):
    blog = models.ForeignKey('Blog', related_name='authors')

class Entry(models.Model):
   author = models.ForeignKey('Author', related_name='entries')
   published_on = models.DateTimeField(auto_now_add=True)

Given a particular blog's primary key, how would I retrieve a queryset of entries such that the queryset contains only the single most recent entry of each author?

Keith Morris
  • 275
  • 2
  • 9

2 Answers2

1

Found the answer here:

Django query that get most recent objects from different categories

authors = Author.objects.annotate(latest_entry_published_on=Max('entries__published_on')) 
entries = Entry.objects.filter(published_on__in=[a.latest_entry_published_on for a in authors])
Community
  • 1
  • 1
Keith Morris
  • 275
  • 2
  • 9
0

I'd try something like:

Entry.objects.order_by('-published_on').values_list('author_id').distinct()
dan-klasson
  • 13,734
  • 14
  • 63
  • 101