2015-08-24 72 views
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() 

但是,這些數據我終於在瀏覽器上的DRF頁面顯示一切爲空。 enter image description here

我懷疑問題是與序列化,因爲查詢集工作properly.Any幫助

回答

0

抱歉,我不能發表評論,所以..

我不明白很多關於查詢集,但是,試試這個:

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:你可以給我們打印QuerySet在殼?

PD 2:我不能留下評論,再次抱歉