从Django queryset json输出中剥离模型pk和字段文本

时间:2016-07-22 22:25:29

标签: json django django-queryset

在django的视图中,我想输出转换为json的查询集,而不输出模型,pk和字段文本。

我的观看代码:

s = serializers.serialize('json', Item.objects.get(id=actuators_id)])
o = s.strip("[]")
return HttpResponse(o, content_type="application/json")

我得到的是:

{"model": "actuators.acutatoritem", "pk": 1, "fields": {"name": "Environment Heater", "order": 1, "controlid": "AAHE", "index": "1", "param1": "", "param2": "", "param3": "", "current_state": "unknown"}}

我整天都没有得到的是:

{"name": "Environment Heater", "order": 1, "controlid": "AAHE", "index": "1", "param1": "", "param2": "", "param3": "", "current_state": "unknown"}

我可以从输出中删除模型,pk和字段文本吗?

1 个答案:

答案 0 :(得分:0)

使用simplejson将qs转换为python dict {}

import simplejson
s = serializers.serialize('json', Item.objects.filter(id=actuators_id)])

js = simplejson.loads(s)
//select the key needed and return the response   
s = js[0]['fields']

return HttpResponse(str(s), content_type="application/json")