python - 按年和月分组数据 | 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
谢谢!
编辑:
请看下面的答案
解决方案
我已经实现了这一点,我仍然不知道它是否可行,但瞧。这是一个好的开始。
[
{
"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
推荐阅读
- python - 通过 for 循环进行第二次迭代时出现“熊猫”错误
- php - symfony4 在表单中注入参数
- c# - 尝试使用 c# 从 wsdl 获取数据
- django - Django 反向关系序列化器
- json - 离子读取本地 JSON 文件
- php - 如何通过 PHP CURL POST 上传文件
- javascript - 用于书签的 Chrome 扩展 API
- reactjs - 如何防止 Visual Studio 代码在我的 JSX 中放置换行符?
- reporting-services - SSRS 无法识别条形码表达式中的数据集
- excel - 如何添加 COUNTIFS,我查看了其他主题但没有用