如何编写Django查询来聚合集体博客的每个作者最近发布的条目?

时间:2015-01-23 01:35:37

标签: python django django-models django-queryset

假设以下简化模型:

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)

鉴于特定博客的主键,我如何检索条目的查询集,以便查询集仅包含每个作者的单个最新条目?

2 个答案:

答案 0 :(得分:1)

在这里找到答案:

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

答案 1 :(得分:0)

我会尝试类似的事情:

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