1.对象
对于Django的Queryset<Queryset [object,object,object]>这种关于django的Querysetset对象这种是不能用python的json方法,需要用到django的 serializers模块
传递给 serialize 方法的参数有二点:
a.个序列化目标格式,
b.一个是序列号的对象QuerySet. (事实上,第二个参数可以是任何可迭代的Django Model实例,但它很多情况下就是一个QuerySet).
from django.conf.urls import urlfrom django.contrib import adminfrom app01 import viewsfrom app02 import views as v2from app03 import views as v3urlpatterns = [ url(r'^xuliehua/', v3.xuliehua), url(r'^get_data/', v3.get_data),]
Title 用户列表
Title { % for row in user_list %} { { row.id }} { { row.username }} { { row.email }} { % endfor %}
from django.shortcuts import render,HttpResponsefrom app01 import modelsimport jsondef xuliehua(request): return render(request,'xuliehua.html')def get_data(request): from django.core import serializers ret ={ 'status':True,'data':None} try: # 1.对象转字符串(序列化) user_list = models.UserInfo.objects.all() # QuerySet【obj,obj,obj】 ret['data'] = serializers.serialize("json",user_list) # 通过Django 内置序列化 except Exception as e: ret['status'] = False result = json.dumps(ret) return HttpResponse(result)
2.字典
关于python一些内置一些类型(例如:字典,列表,元祖。。。)的序列化,就用json 就可以了
Title 用户列表
from django.shortcuts import render,HttpResponsefrom app01 import modelsimport jsondef xuliehua(request): return render(request,'xuliehua.html')def get_data(request): from django.core import serializers ret ={ 'status':True,'data':None} try: # 2.字典转字符串(序列化) user_list = models.UserInfo.objects.all().values('id','username') ret['data'] = list(user_list) # user_list最外面querySet,里面是字典;list(user_list)相当于把querySet list化 except Exception as e: ret['status'] = False result = json.dumps(ret) return HttpResponse(result)
3.元组
Title 用户列表
from django.shortcuts import render,HttpResponsefrom app01 import modelsimport jsondef xuliehua(request): return render(request,'xuliehua.html')def get_data(request): from django.core import serializers ret ={ 'status':True,'data':None} try: # 3.元组转字符串(序列化) user_list = models.UserInfo.objects.all().values_list('id', 'username') ret['data'] = list(user_list) # user_list最外面querySet,里面是元组;list(user_list)相当于把querySet list化 except Exception as e: ret['status'] = False result = json.dumps(ret) return HttpResponse(result)