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)
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值