我的简单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()
我怀疑问题在于序列化,因为查询集正常工作。任何帮助
答案 0 :(得分:0)
我对QuerySet了解不多,但是,试试这个:
class LineGraphSerializer(serializers.Serializer):
total_prescriptions = serializers.SerializerMethodField()
timeline = serializers.SerializerMethodField()
def get_total_prescriptions(self,*args, **kwargs):
#print kwargs and look data
#return <requiere data>
def get_timeline(self,*args, **kwargs):
#print kwargs and look data
#return <requiere data>
PD 1:你能在shell上给我们打印QuerySet吗?
PD 2:我还不能发表评论,再次抱歉