Richard
Richard

Reputation: 65510

Serializing Django queryset to JSON: getting AttributeError 'tuple' object has no attribute '_meta'

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)

But this gives me:

AttributeError at /api/1.0/bnf_code: 'tuple' object has no attribute '_meta'

At the line:

return JsonResponse(serializers.serialize('json', data), safe=True) 

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?

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'

Upvotes: 0

Views: 2798

Answers (1)

catavaran
catavaran

Reputation: 45555

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) 

Upvotes: 2

Related Questions