• 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 '''
  • 相关阅读:
    testDecoration
    python装饰器详解
    开闭原则, 对扩展开放、对修改关闭
    使用元类 编写ORM
    Python 实现累加计数的几种方法
    python 查找目录下 文件名中含有某字符串的文件
    android应用程序的混淆打包规范
    自定义Tabs
    android-Service
    Loader异步装载器
  • 原文地址:https://www.cnblogs.com/Alexephor/p/11318182.html
Copyright © 2020-2023  润新知