【问题标题】:Renaming a field on a Django queryset with group by使用 group by 重命名 Django 查询集上的字段
【发布时间】: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


    【解决方案1】:

    您可以通过使用注释的名称来做到这一点,因此:

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

    【讨论】:

    • 此解决方案返回具有正确名称的字段,但不只返回月份 id,它返回完整的时区/日期格式:{ "month_id": "2021-01-01T00: 00:00-03:00" }
    • @PatrickFreitas:啊,那你可能在找ExtractMonth,而不是TruncMonth
    • 太棒了!这正是我想要的,谢谢!
    猜你喜欢
    • 1970-01-01
    • 2015-09-12
    • 2022-01-26
    • 1970-01-01
    • 2021-04-05
    • 2017-12-23
    • 1970-01-01
    • 1970-01-01
    • 2013-06-25
    相关资源
    最近更新 更多