繁体   English   中英

使用 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')

此查询集的结果返回为:

[{"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')))

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

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

或者如果你想提取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=ExtractMonth('date_joined')
).annotate(qtd=Count('id')).order_by('month_id')

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM