Django之序列化
Posted alexephor
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Django之序列化相关的知识,希望对你有一定的参考价值。
Django中的序列化主要是在数据库中扫描数据返回给客服端用户
serializers
1 from django.core import serializers 2 3 ret = models.UserInfo.objects.all() 4 data = serializers.serialize("json", ret)
json.dumps
1 import json 2 3 #ret = models.UserInfo.objects.all().values(‘username‘) 4 ret = models.UserInfo.objects.all().values_list(‘username‘) 5 6 ret=list(ret) 7 8 result = json.dumps(ret)
json.dumps无法处理datetime时期格式可以自己定义
1 import json 2 from datetime import date 3 from datetime import datetime 4 5 d=datetime.now() 6 7 8 class JsonCustomEncoder(json.JSONEncoder): 9 10 def default(self, field): 11 12 if isinstance(field, datetime): 13 return field.strftime(‘%Y-%m-%d %H:%M---%S‘) 14 elif isinstance(field, date): 15 return field.strftime(‘%Y-%m-%d‘) 16 else: 17 return json.JSONEncoder.default(self, field) 18 19 20 ds = json.dumps(d, cls=JsonCustomEncoder) 21 22 print(ds) 23 print(type(ds)) 24 25 26 27 ‘‘‘ 28 Supports the following objects and types by default: 29 30 +-------------------+---------------+ 31 | Python | JSON | 32 +===================+===============+ 33 | dict | object | 34 +-------------------+---------------+ 35 | list, tuple | array | 36 +-------------------+---------------+ 37 | str | string | 38 +-------------------+---------------+ 39 | int, float | number | 40 +-------------------+---------------+ 41 | True | true | 42 +-------------------+---------------+ 43 | False | false | 44 +-------------------+---------------+ 45 | None | null | 46 +-------------------+---------------+ 47 48 ‘‘‘
以上是关于Django之序列化的主要内容,如果未能解决你的问题,请参考以下文章