![](/img/trans.png)
[英]How can I obtain all posts published in the last hour from a blog (built with django) with a queryset?
[英]How can I write a Django query to aggregate the most recently published entry for each author of a collective blog?
假定以下簡化模型:
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)
給定特定博客的主鍵,我將如何檢索條目的查詢集,以便該查詢集僅包含每個作者的單個最新條目?
在這里找到答案:
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.