在django中使用templateHTMLrenderer时无法解析json对象

时间:2016-01-25 20:59:54

标签: javascript json django

我从django和JSON开始,我正在尝试使用以下代码发送JSON患者列表:

class JSONResponse(HttpResponse):
    """
    An HttpResponse that renders its content into JSON.
    """
    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')

在records.html中,我有这个javascript代码:

<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, I'm trying to figure out how to do it

然而,当打印数据时(以字符串形式查看我的内容)我收到类似的内容

 [<Patient: Patient object>, <Patient: Patient object>, <Patient:  Patient object>, <Patient: Patient object>, <Patient: Patient object>, <Patient: Patient object>, <Patient: Patient object>]

根据我的理解,在使用Response时没有必要序列化数据,所以我没有这样做。我只是想获取患者列表并打印他们的firstName。对此有何帮助?

1 个答案:

答案 0 :(得分:0)

如果你想要做很长的事情,你应该只使用Django提供的JsonResponse类:https://docs.djangoproject.com/en/1.9/ref/request-response/#jsonresponse-objects。但是因为看起来你正在使用DjangoRestFramework,在这种情况下,你可能想要考虑只创建一个序列化器类,然后只创建一个ViewSet。

in seralizers.py:

from rest_framework import serializers

class MySerializer(serializers.ModelSerializer):

  class Meta:
    model = MyModel

in views.py:

from rest_framework import viewsets
from .serializers import MySerializer

class MyViewSet(viewsets.ModelViewSet):

  serializer_class = MySerializer
  queryset = MyModel.objects.all()

in urls.py:

from rest_framework import routers
from .views import MyViewSet

router = routers.SimpleRouter()
router.register(r'mymodel', MyViewSet)