I am trying to do a survey application in django. My model is as follows:
class mymodel(models.Model):
resptype = models.ForeignKey(Response)
ques = models.ForeignKey(Question)
response = models.CharField(max_length=5, blank=True)
Here i am using rest framework to send data to my front end. Right now i have my api
defined as follows:
class mymodelList(APIView):
def get(self, request, format=None):
surveydata = mymodel.objects.all()
serialized_surveydata = mymodelSerializer(surveydata, many=True)
return Response(serialized_surveydata.data)
In my app, I have a standard set of 16 questions with multiple choice responses and the choice is saved in the response column in the model.
Now what I am trying to achieve is to calculate the count of responses for each question . ie. For question 1, what is the count that a person responded with 1 or 2 or etc.
Also i would like to know how to send the calculated counts through another json field from the rest framework because I don't have any model defined separately for this data.
EDIT:
This command did the trick for my query but i still not able to figure out how to send it to the front end as a serialized object.
x = mymodel.objects.values('ques','response').order_by().annotate(number_of_responses=Count('response'))
That's not really a great structure for your model, it would probably be easier to create separate Question and Choice classes. The Django tutorial actually uses this type of application as an example... take a look at that for some guidance
Check @detail_route or @list_route from viewsets depending on if you want to show this info per question o for all questions at once.
This will allow you to define a custom endpoint to request the information you are asking for. To do so, you may also need to define a custom serializer to pass extra data or a filter if you want to filter by question, user, etc.