【问题标题】:Issues with Django data serializationDjango 数据序列化的问题
【发布时间】: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


    【解决方案1】:

    对不起,我不能离开 cmets,所以..

    我不太了解那个 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:我还不能离开 cmets,再次抱歉

    【讨论】:

      猜你喜欢
      • 2011-05-30
      • 1970-01-01
      • 1970-01-01
      • 2015-10-22
      • 2021-11-17
      • 2017-06-02
      • 2016-12-09
      • 2020-01-03
      • 1970-01-01
      相关资源
      最近更新 更多