第一种方式:
利用seriallizers
这个方法,官网的解释说:将复杂的数据结构变成json、xml或者其他的格式
import json
from django.core import serializers
def area2(request,id):
data = {}
province = serializers.serialize("json",AreaInfo.objects.filter(parea__isnull=True))
data["data"] = json.loads(province)
return JsonResponse(data,safe=False)
输出的结果如下:
{
data: [
{
model: "myapp1.areainfo",
fields: {
title: "北京市",
parea: null
},
pk: 110000
},
{
model: "myapp1.areainfo",
fields: {
title: "天津市",
parea: null
},
pk: 120000
},
{
model: "myapp1.areainfo",
fields: {
title: "河北省",
parea: null
},
pk: 130000
},
第二种方法,使用list,这也是三种中最简单的
def area2(request,id):
data = {}
province = AreaInfo.objects.filter(parea__isnull=True).values()
data["data"] = list(province)
return JsonResponse(data,safe=False)
结果如下:
{
data: [
{
id: 110000,
title: "北京市",
parea_id: null
},
{
id: 120000,
title: "天津市",
parea_id: null
},
{
id: 130000,
title: "河北省",
parea_id: null
},
{
id: 140000,
title: "山西省",
parea_id: null
},
第三种方法比较原始,利用for循环拼装:
def area2(request,id):
data = AreaInfo.objects.filter(parea__isnull=True)
list=[]
for province in data:
list.append([province.id,province.title])
data={‘data‘:list}
return JsonResponse(data,safe=False)
运行结果如下:
{
data: [
[
110000,
"北京市"
],
[
120000,
"天津市"
],
[
130000,
"河北省"
],
[
140000,
"山西省"
],
[
150000,
"内蒙古自治区"
],
[
210000,
"辽宁省"
],
原文地址:http://blog.51cto.com/853056088/2313833
时间: 2024-10-10 00:20:29