django 3种返回json方法
from django.http import JsonResponse, HttpResponse
from django.shortcuts import render
from app01.models import Book
# Create your views here.
def get_book(request):
all_book = Book.objects.all()
d = []
for i in all_book:
d.append({'name': i.name})
return JsonResponse(d, safe=False)
def get_book2(request):
from django.forms.models import model_to_dict
all_book = Book.objects.all()
d = []
for i in all_book:
d.append(model_to_dict(i))
return JsonResponse(d, safe=False)
def get_book3(request):
from django.core.serializers import serialize
d = serialize('json', Book.objects.all())
# return HttpResponse(d)
return HttpResponse(d)
原文地址:https://www.cnblogs.com/iiiiiher/p/9527083.html
时间: 2024-10-12 02:28:37