第一种方式:
利用seriallizers
这个方法,官网的解释说:将复杂的数据结构变成json、xml或者其他的格式
importjsonfromdjango.coreimportserializersdefarea2(request,id):data = {} province = serializers.serialize("json",AreaInfo.objects.filter(parea__isnull=True)) data["data"] = json.loads(province)returnJsonResponse(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,这也是三种中最简单的 货运app开发找上海捌跃网络科技有限公司
defarea2(request,id):data = {} province = AreaInfo.objects.filter(parea__isnull=True).values() data["data"] = list(province)returnJsonResponse(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循环拼装:
defarea2(request,id):data = AreaInfo.objects.filter(parea__isnull=True) list=[]forprovinceindata: list.append([province.id,province.title]) data={'data':list}returnJsonResponse(data,safe=False)
运行结果如下:
{data: [[110000,"北京市"],[120000,"天津市"],[130000,"河北省"],[140000,"山西省"],[150000,"内蒙古自治区"],[210000,"辽宁省"],
转自:http://blog.51cto.com/853056088/2313833