Reputation: 14408
I want to serialize a custom object in json format, where entryData is a list of my domain object. Something like this:
{
"total":2,
"current":1,
"entryData":[
{
"id":1,
"version":0,
"name":"Default Station"
},
{
"id":2,
"version":3,
"name":"Default Station 1"
}
]
}
Here what I have done to get json output in one of my attempt:
def ground_station_listgrid(request):
entryData = serializers.serialize("json", GroundStation.objects.all())
response_data = {}
response_data['totalPages'] = 2
response_data['currentPage'] = 1
response_data['entryData'] = entryData
return HttpResponse(json.dumps(response_data),mimetype='application/json')
but the result is entryData evaluated as a string, with quotes escaped:
{
"totalPages": 1,
"currentPage": 1,
"entryData": "[{\"pk\": 1, \"model\": \"satview.groundstation\", ....
I have also tryed to do something like this:
def ground_station_listgrid(request):
response_data = {}
response_data['totalPages'] = 1
response_data['currentPage'] = 1
response_data['entryData'] = GroundStation.objects.all()
return HttpResponse(json.dumps(response_data),mimetype='application/json')
But I get this exception: [<GroundStation: nome>, <GroundStation: nome>, <GroundStation: nome>] is not JSON serializable
Can someone please poin me in right direction?
Thanks in advance Marco
Upvotes: 3
Views: 2809
Reputation: 473863
You can use model_to_dict():
def ground_station_listgrid(request):
data = [model_to_dict(instance) for instance in GroundStation.objects.all()]
response_data = {}
response_data['totalPages'] = 1
response_data['currentPage'] = 1
response_data['entryData'] = data
return HttpResponse(json.dumps(response_data),mimetype='application/json')
Though I prefer to use included in django batteries: django.core.serializers, but, since you have a custom json response, model_to_dict()
appears to be the way to go.
There are other options here (like use of values_list()
):
Upvotes: 7