VIII. serialization
About serialization in Django the primary application is to return the data retrieved from the database to the client user, and the special AJAX request is typically returned in JSON format.
1, serializers
1 from Import serializers 2 3 ret = models. BookType.objects.all ()4 5 data = Serializers.serialize ("JSON ", ret)
2, Json.dumps
1 Import JSON 2 3 # ret = models. BookType.objects.all (). VALUES (' caption ')4 ret = models. BookType.objects.all (). Values_list ('caption')5 6 ret=list (ret)7 8 result = Json.dumps (ret)
Because the datetime date cannot be processed by json.dumps, the extension can be done by customizing the processor, such as:
1 ImportJSON2 fromDatetimeImportDate3 fromDatetimeImportdatetime4 5 classJsoncustomencoder (JSON. Jsonencoder):6 7 defDefault (Self, field):8 9 ifisinstance (field, datetime):Ten returnO.strftime ('%y-%m-%d%h:%m:%s') One elifisinstance (field, date): A returnO.strftime ('%y-%m-%d') - Else: - returnJSON. Jsonencoder.default (Self, field) the - - #ds = Json.dumps (d, Cls=jsoncustomencoder)
Python Path--web--2--django-10--serialization