【发布时间】:2021-08-10 01:06:34
【问题描述】:
我按月份统计今年注册的用户数。
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')
这个查询集的结果它被返回为:
[{"date_joined__month": 1,"qtd": 5},{"date_joined__month": 2,"qtd": 35}]
我想将字段“date_joined__month”的名称更改为“month_id”并保持计数和按逻辑分组。
我已经尝试添加以下方法,但它们都返回了完整的日期格式,而只返回了月份 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')))
【问题讨论】:
标签: python django rest django-rest-framework django-queryset