I'm just starting out with django and JSON, and I'm attempting to send a list of patients in JSON using the code below:
class JSONResponse(HttpResponse):
"""
An HttpResponse that converts content into JSON format.
"""
def __init__(self, data, **kwargs):
content = JSONRenderer().render(data)
kwargs['content_type'] = 'application/json'
super(JSONResponse, self).__init__(content, **kwargs)
@api_view(('GET',))
@renderer_classes((TemplateHTMLRenderer,))
@csrf_exempt
def patient_list(request):
"""
List all records or create a new snippet.
"""
if request.method == 'GET':
#data = Patient.objects.all()
data= Patient.objects.all()
#serializer = PatientSerializer(data, many=True)
#return JSONResponse(serializer.data)
return Response({'patients': data}, template_name='records.html')
In the records.html file, there is the following JavaScript code:
<script type="text/javascript">
var data = "{{patients}}";
var parsed = JSON.parse(data);
</script>
...
<h2> <script type="text/javascript">document.write(data);</script></h2> This is not actually true, as I am exploring how to achieve this
However, when printing the data (as a string just to see what's available), it shows something like this:
[<Patient: Patient object>, <Patient: Patient object>, <Patient: Patient object>, <Patient: Patient object>, <Patient: Patient object>, <Patient: Patient object>, <Patient: Patient object>]
My understanding is that serialization is not required when using Response. I simply want to retrieve the list of patients and display their first name for example. Any guidance on accomplishing that?