2

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 ?

1 Answer 1

1

You can use a ModelSerializer for the same class the viewset represents (Prescription in your case) and add the custom fields using ReadOnlyField. Something like:

class LineGraphSerializer(serializers.ModelSerializer):
    pr_id__count = serializers.ReadOnlyField()
    month = serializers.ReadOnlyField()

    class Meta:
        model = Prescription
        fields = ['pr_id__count', 'month']

It might need some tweaks, but that's the general idea.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.