Python---serialization in Django

Source: Internet
Author: User
Tags serialization

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.