假设以下简化模型:
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)
鉴于特定博客的主键,我如何检索条目的查询集,以便查询集仅包含每个作者的单个最新条目?
答案 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()