Sorry for my English. I have some data from another server, but I need to output this data like JSON.
if i print response in console:
JavaScript
x
11
11
1
{
2
'responseStatus': {
3
'status': [],
4
},
5
'modelYear': [
6
1981,
7
1982
8
9
]
10
}
11
but, if i return this response like HttpResponse
i have an error
AttributeError: ‘str’ object has no attribute ‘_meta’
this my code:
JavaScript
1
3
1
data = serializers.serialize('json', response, ensure_ascii=False)
2
return HttpResponse(data, content_type="application/json")
3
UPD:
I tried with this:
JavaScript
1
6
1
from django.http import JsonResponse
2
3
def some_view(request):
4
5
return JsonResponse(response, safe=False)
6
but have error:
Object of type ‘ModelYears’ is not JSON serializable
UPD:
I did like this:
JavaScript
1
7
1
import json
2
from django.http import JsonResponse
3
4
def some_view(request):
5
6
return JsonResponse(json.loads(response))
7
but have error:
JavaScript
1
2
1
the JSON object must be str, bytes or bytearray, not 'ModelYears'
2
Advertisement
Answer
The Django docs says the following about the serializers
framework:
Django’s serialization framework provides a mechanism for “translating” Django models into other formats.
The error indicates that your variable response
is a string
and not an Django model object. The string seems to be valid JSON
so you could use JsonResponse:
JavaScript
1
6
1
import json
2
from django.http import JsonResponse
3
4
# View
5
return JsonResponse(json.loads(response))
6