0
我簡單models.py看起來是這樣的:問題和Django的數據序列化
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是今天的日期和起始日期是之日起六個月一個月的back.This如預期的查詢集的作品,我已經證實了這一點上的Django貝殼。
我需要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()
我懷疑問題是與序列化,因爲查詢集工作properly.Any幫助