第一种方式:
利用seriallizers
这个方法,官网的解释说:将复杂的数据结构变成json、xml或者其他的格式
1
2
3
4
5
6
7
8
9
|
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,这也是三种中最简单的
1
2
3
4
5
6
7
|
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循环拼装:
1
2
3
4
5
6
7
8
9
|
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