我的简单型号.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')
其中结束日期是今天的日期,开始日期是六个月的日期回来。这个queryset按预期工作,我已经在django shell上证实了这一点。你知道吗
我需要JSON格式的数据,因为它最终需要发送到角度的折线图。我的视图.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)
还有我的序列化程序.py看起来像这样:
from rest_framework import serializers
class LineGraphSerializer(serializers.Serializer):
total_prescriptions = serializers.IntegerField()
timeline = serializers.DateField()
我怀疑问题出在序列化上,因为queryset可以工作好的。有吗救命
抱歉,我不能留言,所以。。你知道吗
我不太了解QuerySet,但是,试试这个:
警察1:你能给我们壳牌公司打印的查询表吗?你知道吗
警察2:我还不能留言,再次抱歉
相关问题 更多 >
编程相关推荐