def get_data (req): Ret= {'Status': True,'Data': None}Try: User_list=models. User.objects.all () ret['Data']=user_list #TypeError at/get_data.html #<queryset [<user:dwafwaa>, <user:fwaf>, <user:faw>, <user:fwafwa> ;] > isNot JSON serializable
#json只能序列化基本数据类型, for objects that cannot be serialized, we need to use serializers.serialize except Exception ase:ret['Status']=False Result= Serializers.serialize ("JSON", ret) #typeError: ' Module ' object is not callable #serializers只能对queryset进行序列化
#这里中ret含有基本数据类型, Serializers.serialize cannot be serializedreturnHttpResponse (Result)
Correct use:
def get_data (req): Ret= {'Status': True,'Data': None}Try: User_list=models. User.objects.all () ret['Data']=serializers.serialize ("JSON", User_list) #TypeError at/get_data.html #<queryset [<user:dwafwaa>, <user:fwaf>, <user:faw>, <User:fwafwa>]> isNot JSON serializable #去数据库中取数据时, formatted queryset #其中可以是对象, list, dictionary, wrapped in the outside [] list #对于对象的序列化, we need to use serial Izers.serialize ( "JSON" , user_list) is processed #对于其他基本类型我们只需要稍微进行转换即可 and converted directly to a list (by Queryset) lists (user_list) to #在前端获取的数据就不需要在进行一次转义了 (for S Erialize, we need to do an escape, we don't use serialize here, so we don't need to escape except Exception ase:ret['Status']=False Result=json.dumps (ret)returnHttpResponse (result)
Front-End use:
function InitData () {$.ajax ({URL:"/get_data.html", type:"Get", DataType:"JSON", Success:function (data) {if(data.status) {console.log (data.data)varv =Json.parse (Data.data); #对于我们获取的data. Data corresponds to the serializers.serialize serialized above and is serialized by JSON, so we need to do json.parse again to get the console again. Log (v)}})}
Python---serialization in Django