[英]How to group_by an annotated field for django querysets?
她是我這樣的模型:
class Article(models.Model):
title = models.CharField(max_length=50, blank=True)
author = models.CharField(max_length=50, blank=True)
created_at = models.DateTimeField(auto_now_add=True)
我想返回一個查詢集,它是 group_by created_at 月份,我為查詢集注釋了一個created_month
字段:
queryset = Article.objects.annotate(created_month=TruncMonth('created_at'))
但是當我嘗試通過添加.values('created_at')
來按created_at
分組時,如下所示:
queryset = Article.objects.annotate(created_month=TruncMonth('created_at')).values('created_month').order_by('-created_month')
查詢集僅返回created_month
字段。 我該怎么做才能像這樣獲得整篇文章查詢集 group_by created_month
:
[
{
'created_month': '2021-07',
'articles': [
{'title': 'Article 1', 'author': ...}
]
},
{
'created_month': '2021-06',
'articles': [
{'title': 'Article 2', 'author': ...},
{'title': 'Article 3', 'author': ...}
]
}
]
您必須進行一些后處理才能獲得您喜歡的輸出格式,因為我相信目前沒有任何 django API 支持這種格式。 但首先,你需要使用values
上created_month
以及title
和author
。 所以像:
queryset = Article.objects.annotate(
created_month=TruncMonth('created_at')
).values('created_month', 'title', 'author').order_by('-created_month')
grouped_by_month_result = {}
for q in queryset:
if q['created_month'] in result:
grouped_by_month_result[q['created_month'].append(
{'title': q['title'], 'author': q['author']}
)
else:
grouped_by_month_result[q['created_month'] = [{'title': q['title'], 'author': q['author']}]
result = []
for k, v in grouped_by_month_result.items():
result.append({
'created_month': k,
'articles': v,
})
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.