[Django]-Django: custom object json serialization

7👍

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()):

👤alecxe

Leave a comment