python项目篇-django查询数据库得到的结果序列化成json字符串

class adminIncome(View):
 
    def get(self, request):
 
    1、方法一:(for in 循环遍历model)
    	# 定义一个空列表
    	json_list = []
    	incomes = incomeAccount.objects.all()[:10]
    	for i in adminIncome:
            json_dict["id"] = i.id
	        json_dict["totalIncome"] = i.totalIncome
	        json_dict["dayIncome"] = i.dayIncome
	        json_dict["remarkIncome"] = i.remarkIncome
	        json_dict["totalBath"] = i.totalBath
	        json_dict["totalBathHouse"] = i.totalBathHouse
	        json_dict["totalHouse"] = i.totalHouse
	        json_dict["totalPay"] = i.totalPay
	
	        json_list.append(json_dict)

    ret1 = json.dumps(json_list)
    print(ret1,type(ret1))
    return render(request,'admin_chartIncome.html',{"ret": json.dumps(ret1)})
 
    2、方法二:(django自带的serializers序列化model)(推荐使用此方法)
        import json 
        from django.core import serializers
        json_data = serializers.serialize('json', incomes)
        json_data = json.loads(json_data)
        from django.http import HttpResponse, JsonResponse
        return JsonResponse(json_data, safe=False)
 
    3、方法三:(model_to_dict方法)
        from django.forms.models import model_to_dict
        for good in goods:
            json_dict = model_to_dict(incomes)
            json_list.append(json_dict)

你可能感兴趣的:(Python,Django,项目,Json)