• Django ORM QuerySet转json


    下面是Django中两种常用的ORM查询
    models.Component.objects.filter(...).all()

    models.Component.objects.values(...)

    第一种我们可以使用serializers.serialize("json", c)方法来转json格式字符串
    c = models.Component.objects.filter(id=1).all()
    components = serializers.serialize("json", c)
    data = json.dumps({"value": components})
    print(data)


    就成功的转成如下json数据了

    {"value": "[
    {\"model\": \"Storage.component\",
    \"pk\": 1,
    \"fields\": {
    \"name\": \"\u5e95\u5ea7\",
    \"code\": \"1-10\",
    \"type\": 0,
    \"important\": 0,
    \"product\": 1,
    \"num\": 12,
    \"storage\": null,
    \"location\": null,
    \"remark\": \"\"}
    },
    {\"model\": \"Storage.component\",
    \"pk\": 2,
    \"fields\": {
    \"name\": \"\u51f8\u900f\u955c\",
    \"code\": \"1-20\",
    \"type\": 1,
    \"important\": 1,
    \"product\": 1,
    \"num\": 3,
    \"storage\": null,
    \"location\": null,
    \"remark\": \"\"}}
    ]"}

    虽然看起来有点难受,但至少能用,像我这种强迫症直接就放弃了。。。

    第二种如果还是使用serializers.serialize("json", c)方法来转json你就会发现直接报错了
    c = models.Component.objects.filter(id=1).values("name", "code")
    components = serializers.serialize("json", c)
    # 这里就直接报错了
    # AttributeError: 'dict' object has no attribute '_meta'

    所以只能换种方法

    c = models.Component.objects.filter(id=1).values("name", "code")
    print(c)
    # <QuerySet [{'name': '底座', 'code': '1-10'}, {'name': '凸透镜', 'code': '1-20'}]>
    当我们打印出来看的时候会发现这QuerySet其实里面就是放了两个字典,那就正好一个天然json块,那就直接拿出来就好了

    l = []
    for a in c:
    l.append(a)
    js = json.dumps({"value": l}, ensure_ascii=False)
    print(js)
    # {"value": [{"name": "底座", "code": "1-10"}, {"name": "凸透镜", "code": "1-20"}]}

    当然还可以把它做成通用方法

    def dictFetchOrm(para):
    resDic=[]
    for i in para:
    resDic.append(i)
    return json.dumps(resDic, ensure_ascii=False)
    ————————————————
    版权声明:本文为CSDN博主「simple-soul」的原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接及本声明。
    原文链接:https://blog.csdn.net/UmGsoil/article/details/123924654

  • 相关阅读:
    tensorflow学习之路---Session、Variable(变量)和placeholder
    tensorflow学习之路---简单的代码
    python之路:发附带文件的邮件
    pythong中的全局变量的调用和嵌套函数中变量的使用
    python字符串
    Python之路:画空心矩形
    ajax jsonp请求报错not a function的解决方案
    《beyond jquery》读书笔记1
    移动端video标签默认置顶的解决方案
    css中的视距perspective和视差效果
  • 原文地址:https://www.cnblogs.com/hongdoudou/p/16794926.html
Copyright © 2020-2023  润新知