使用 group by 重命名 Django 查询集上的字段

Renaming a field on a Django queryset with group by

我是按月统计今年的注册用户。

from rest_framework.response import Response
from django.db.models.functions import TruncMonth
from django.db.models import Count
from django.db.models import F

return Response(User.objects
    .filter(date_joined__year=timezone.now().year)
    .annotate(month=TruncMonth('date_joined'))
    .values('month')
    .annotate(qtd=Count('id'))
    .values('date_joined__month', 'qtd')

此查询集的结果已 return编辑为:

[{"date_joined__month": 1,"qtd": 5},{"date_joined__month": 2,"qtd": 35}]

我想将字段名称“date_joined__month”更改为“month_id”并且保持计数和逻辑分组。

我已经尝试添加以下方法,但它们都return编辑了完整的日期格式而不是return只有月份 ID:"month_id" : "2021-01-07T15:26:53.080136Z"

.annotate(month_id=F('date_joined__month'))
.values('qtd', 'month_id'))

or

.values('qtd', month_id=F('date_joined__month')))

您可以使用注释的名称来执行此操作,因此:

return Response(User.objects.filter(
    date_joined__year=timezone.now().year
).values(
    <b>month_id=</b>TruncMonth('date_joined')
).annotate(qtd=Count('id')).<b>order_by('month_id')</b>

或者如果你想提取 Month 本身,你可以使用 ExtractMonth [Django-doc]

from django.db.models.functions import ExtractMonth

return Response(User.objects.filter(
    date_joined__year=timezone.now().year
).values(
    month_id=<b>ExtractMonth(</b>'date_joined'<b>)</b>
).annotate(qtd=Count('id')).order_by('month_id')