将Django queryset序列化为JSON:获取AttributeError'tuple'对象没有属性'_meta' [英] Serializing Django queryset to JSON: getting AttributeError 'tuple' object has no attribute '_meta'
本文介绍了将Django queryset序列化为JSON:获取AttributeError'tuple'对象没有属性'_meta'的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在使用Django 1.8.这是我的看法:
I'm using Django 1.8. This is my view:
from django.http import JsonResponse
...
query = "SELECT * FROM frontend_chemical WHERE id LIKE %s"
cursor.execute(query, (code + "%",))
data = cursor.fetchall()
print data
return JsonResponse(serializers.serialize('json', data), safe=False)
但这给了我:
AttributeError at /api/1.0/bnf_code: 'tuple' object has no attribute '_meta'
在线:
return JsonResponse(serializers.serialize('json', data), safe=True)
在控制台中,我可以看到我的数据已返回OK:
In the console, I can see that my data has returned OK:
[(u'0210', u'Stable angina, acute coronary syndromes, and fibrinolysis'), (u'0211', u'Antifibrinolytic drugs and haemostatics'), (u'0212', u'Lipid-regulating drugs'), (u'0213', u'Local sclerosants')]
任何想法可能出什么问题吗?
Any idea what might be going wrong?
更新:我也一直在尝试使用 data = dictfetchall(cursor)
将数据作为字典获取
UPDATE: I've also been trying to get the data as a dictionary, using data = dictfetchall(cursor)
as described here.
但是,这只是在同一位置失败,并带有一个稍微不同的错误:
However, this just fails in the same place with a slightly different error:
AttributeError: 'dict' object has no attribute '_meta'
推荐答案
序列化器仅用于序列化Django模型.要序列化简单的python数据,请使用内置的 json
模块:
Serializers are used to serialize the django models only. To serialize simple python data use the built-in json
module:
import json
return JsonResponse(json.dumps(data), safe=True)
这篇关于将Django queryset序列化为JSON:获取AttributeError'tuple'对象没有属性'_meta'的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文