How do I return JSON without using a template in Django?

前端 未结 9 1584
再見小時候
再見小時候 2020-12-04 07:01

This is related to this question: Django return json and html depending on client python


I have a command line Python API for a Django app. When I access the a

9条回答
  •  情歌与酒
    2020-12-04 07:25

    For rendering my models in JSON in django 1.9 I had to do the following in my views.py:

    from django.core import serializers
    from django.http import HttpResponse
    from .models import Mymodel
    
    def index(request):
        objs = Mymodel.objects.all()
        jsondata = serializers.serialize('json', objs)
        return HttpResponse(jsondata, content_type='application/json')
    

提交回复
热议问题