首页 > 解决方案 > 按年和月分组数据 | django 休息框架

问题描述

我有各种报告,我想以这种方式检索它们:

year: "2019",
months: [
   {
      month: "01",
      reports: [reports for jan]
   }
   {
      month: "02",
      reports: [reports for feb]
   }
    ]

我在一个完整的 Django 项目中实现了类似的东西(见下文),但我无法在 drf 上做同样的事情。

def all_reports_by_month(request):
    reports = Report.objects.all()
    total_reports = reports.count()
    ordered_reports = Report.objects \
        .annotate(month=TruncMonth('date')) \
        .values('month') \
        .annotate(c=Count('id')) \
        .values('month', 'c') \
        .order_by('-month')

    context = {
        'ordered_reports': ordered_reports,
        'total_reports': total_reports

    }
    return render(request, 'dashboard/reports.html', context)

这是我的 DRF 后端报告的当前设置:

模型.py:

class Report(models.Model):
    # each code from shop
    code =  models.ForeignKey(Shop, to_field='code' , on_delete=models.CASCADE)
    clics = models.IntegerField(blank = True, null = True)
    rdv = models.IntegerField(blank = True, null = True)
    date = models.DateField(blank = True, null = True)

序列化程序.py:

class ReportSerializer(serializers.ModelSerializer):
    class Meta:
        model = Report
        fields = '__all__'

视图.py:

class ReportViewSet(viewsets.ModelViewSet):
    queryset = Report.objects.all()
    serializer_class = ReportSerializer

urls.py:

from rest_framework.routers import SimpleRouter
from .views import ReportViewSet 
router = SimpleRouter()

router.register('', ReportViewSet, basename='reports')

urlpatterns = router.urls

谢谢!

编辑:

请看下面的答案

标签: pythondjangodjango-rest-framework

解决方案


我已经实现了这一点,我仍然不知道它是否可行,但瞧。这是一个好的开始。

[
    {
        "month": "2020-06-01",
        "count": 746
    },
    {
        "month": "2020-05-01",
        "count": 746
    }
]

我这样做的方式是创建一个名为 GroupReport 的新模型,我添加了 2 个字段(月和计数)。

模型.py:

class GroupReport(models.Model):
    month = models.DateField()
    count = models.IntegerField(blank = True, null = True)

序列化程序.py:

class ReportGroupMonthSerializer(serializers.ModelSerializer):
     class Meta:
        model = GroupReport
        fields = ('month','count')

视图.py:

class ReportGroupData(ListAPIView):
    queryset = Report.objects.annotate(month=TruncMonth('date')).values('month').annotate(count=Count('id')).values('month', 'count').order_by('-month')
    serializer_class = ReportGroupMonthSerializer

推荐阅读