简体   繁体   中英

How can I write a Django query to aggregate the most recently published entry for each author of a collective blog?

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?

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])

我会尝试类似的东西:

Entry.objects.order_by('-published_on').values_list('author_id').distinct()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM