Mat*_*att 3 django django-models django-orm
让我们说有一个作者,他有书.为了将作者与书面页面的数量一起获取,可以完成以下操作:
Author.objects.annotate(total_pages=Sum('book__pages'))
Run Code Online (Sandbox Code Playgroud)
但是,如果我想分别对科幻和奇幻书籍的页面进行总结呢?我想最终得到一个具有total_pages_books_scifi_pages和total_pages_books_fantasy_pages属性的作者.
我知道我可以做以下事情:
Author.objects.filter(book__category='scifi').annotate(total_pages_books_scifi_pages=Sum('book__pages'))
Author.objects.filter(book__category='fantasy').annotate(total_pages_books_fantasy_pages=Sum('book__pages'))
Run Code Online (Sandbox Code Playgroud)
但是如何在一个查询集中呢?
Vla*_*lov 10
from django.db.models import IntegerField, F, Case, When, Sum
categories = ['scifi', 'fantasy']
annotations = {}
for category in categories:
annotation_name = 'total_pages_books_{}'.format(category)
case = Case(
When(book__category=category, then=F('book__pages')),
default=0,
output_field=IntegerField()
)
annotations[annotation_name] = Sum(case)
Author.objects.filter(
book__category__in=categories
).annotate(
**annotations
)
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2941 次 |
| 最近记录: |