Serialization Django main application on a database in the retrieved data back to the client user, a special request is typically returned to Ajax Json format.
Our data format extracted from the database, there are three: 1, all () returns QuerySet object; 2, values () returns the type QuerySet object dictionary; 3, vlaues_list () QuerySet object tuples returned
1, 2 and 3 kinds may be transmitted to the front end by the rear end json.dumps ().
****** rear end of the object acquired quesyset ******* Import JSON RET = models.BookType.objects.all (). Values ( ' Caption ' ) RET = models.BookType.objects.all (). values_list ( ' Caption ' ) RET = List (RET) Result = json.dumps (RET) ******* distal ajax ****** distal ajax received data JSON.parse (data) to the rear end converting data transfer quesyset
2, for Case 1: QuerySet need serializers acquired serialize objects can be passed to a front end converter
Extracting data from a database back-end ******* ********* from django.core Import serializers RET = models.BookType.objects.all () Data = serializers.serialize ( " JSON " , RET ) # Note serializers only to serialize objects QuerySet conversion ******* front end of the data obtained by converting JSON.parse (data)
Can not be processed due date datetime json.dumps, the processor can be done by custom extensions, such as: Import JSON
from datetime import date from datetime import datetime class JsonCustomEncoder(json.JSONEncoder): def default(self, field): if isinstance(field, datetime): return o.strftime('%Y-%m-%d %H:%M:%S') elif isinstance(field, date): return o.strftime('%Y-%m-%d') else: return json.JSONEncoder.default(self, field) d=datetime.now()
ds = Usage json.dunmps json.dumps (d, cls = JsonCustomEncoder ) # call the base class
step equivalent to:
a=datetime.now()
cls=JsonCustomEncoder()
d=cls.default(a)
ds = json.dumps(d)