码迷,mamicode.com
首页 > 其他好文 > 详细

Django之序列化

时间:2019-08-10 19:30:30      阅读:101      评论:0      收藏:0      [点我收藏+]

标签:serial   now()   inf   model   dict   数据   string   instance   enc   

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之序列化

标签:serial   now()   inf   model   dict   数据   string   instance   enc   

原文地址:https://www.cnblogs.com/Alexephor/p/11318182.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!