簡體   English   中英

如何編寫Django查詢來匯總集體博客的每個作者的最新發布條目?

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

給定特定博客的主鍵,我將如何檢索條目的查詢集,以便該查詢集僅包含每個作者的單個最新條目?

在這里找到答案:

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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM