[英]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 Django查询可从不同类别获取最新对象
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()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.