My models.py is as follows:
class Prescription(models.Model):
pr_id = models.CharField()
date_prescribed = models.DateTimeField()
doctor = models.ForeignKey('Doctor')
pharmacy = models.ForeignKey('Pharmacy')
class Doctor(models.Model):
name = models.CharField()
age = models.IntegerField()
class Pharmacy(models.Model):
name = models.CharField()
status = models.CharField()
Now i need to get the count of all pr_id grouped by month starting from this month and going back 6 months.This data needs to be in json as it needs to be sent to Angular to render a line chart.I am using Django rest framework. My views.py is as follows:
class PrescriptionTrendListView(generics.ListAPIView):
end_date = datetime.utcnow().date()
start_date = end_date + relativedelta(months=-6)
queryset = (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_class = LineGraphSerializer
The queryset works because I tried it in the shell and it gives me the correct data as follows:
>>> queryset
[{'pr_id__count': 16, 'month': datetime.datetime(2015, 2, 1, 0, 0, tzinfo=<UTC>)},
{'pr_id__count': 71, 'month': datetime.datetime(2015, 3, 1, 0, 0, tzinfo=<UTC>)},
{'pr_id__count': 75, 'month': datetime.datetime(2015, 4, 1, 0, 0, tzinfo=<UTC>)},
{'pr_id__count': 96, 'month': datetime.datetime(2015, 5, 1, 0, 0, tzinfo=<UTC>)},
{'pr_id__count': 99, 'month': datetime.datetime(2015, 6, 1, 0, 0, tzinfo=<UTC>)},
{'pr_id__count': 93, 'month': datetime.datetime(2015, 7, 1, 0, 0, tzinfo=<UTC>)},
{'pr_id__count': 39, 'month': datetime.datetime(2015, 8, 1, 0, 0, tzinfo=<UTC>)}]
However,I am not sure how to create the LineGraphSerializer. The two fields that the queryset gives are the count of the Ids and the months which are not in the initial model.How do I go about creating the serializer file ?