【发布时间】:2015-08-24 07:00:24
【问题描述】:
我的简单 models.py 看起来像这样:
from django.db import models
class Prescription(models.Model):
pr_id = models.CharField()
date_prescribed = models.DateTimeField()
doctor = models.ForeignKey()
pharmacy = models.ForeignKey()
我需要的是按月分组的处方总数。 我为上述要求提出的查询集如下:
prescriptions = Prescription.objects.extra(select={'month': connection.ops.date_trunc_sql('month', 'date_prescribed')}).filter(date_prescribed__range=(start_date,end_date)).values('month').annotate(Count('pr_id')).order_by('month')
end_date 是今天的日期,start_date 是六个月后的日期。这个查询集按预期工作,我已经在 django shell 上确认了这一点。
我需要 JSON 格式的数据,因为它最终需要发送到 Angular 中的折线图。我正在使用 Django Rest 框架进行序列化。我的views.py 看起来像这样:
from django.db import connection
from datetime import date
from dateutil.relativedelta import relativedelta
from django.db.models import Count
from rest_framework.decorators import api_view
from rest_framework.response import Response
from testproj.models.Prescription import Prescription
from testproj.serializers.AnalyticsSerializer import LineGraphSerializer
@api_view(['GET'])
def prescription_trend_overview(request):
end_date = date.today()
start_date = date.today() + relativedelta(months=-6)
prescriptions = Prescription.objects.extra(select={'month': connection.ops.date_trunc_sql('month', 'date_prescribed')}).filter(date_prescribed__range=(start_date,end_date)).values('month').annotate(Count('pr_id')).order_by('month')
serializer = LineGraphSerializer(prescriptions, many=True)
return Response(serializer.data)
我的 serializer.py 看起来像这样:
from rest_framework import serializers
class LineGraphSerializer(serializers.Serializer):
total_prescriptions = serializers.IntegerField()
timeline = serializers.DateField()
但是,我最终在浏览器的 DRF 页面中获得的数据显示一切为空。
我怀疑问题出在序列化上,因为查询集工作正常。任何帮助
【问题讨论】:
标签: python django django-rest-framework