简体   繁体   中英

Django Model is not JSON serializable

Im trying to return a dictionary of Django models in JSON format.

I have tried serializers, model_to_dict, json.dump and can't seem to get it working.

a small snippet of the code:

    def get_queryset(self):
        queryset = (Venue.objects.all())
        location = self.request.query_params.get('location', None)
        latitude = location.split('S')[0]
        longitude = location.split('S')[1]
        venue_gaps = {}
        for venue in queryset.iterator():
            locationArray = [y.strip() for y in venue.postcode.split(',')]
            distance = gmaps.distance_matrix([str(latitude) + " " + str(longitude)], [str(locationArray[0]) + " " + str(locationArray[1])], mode='driving')['rows'][0]['elements'][0]
            m = distance["distance"]["value"]
            venue_gaps[m] = venue
        sorted_venues = dict(sorted(venue_gaps.items()))
        return JsonResponse(json.dumps(sorted_venues))

the dictionary I create is a {int:object, int:object, int:object, ....}

I want this to be returned as the response. I keep getting issues such as "TypeError: Object of type object is not JSON serializable"

Use django.core.serializers :

from django.core import serializers

qs = YourModel.objects.filter(foo='bar')
serialized_qs = serializers.serialize('json', qs)

print(serialized_qs)

Docs: https://docs.djangoproject.com/en/2.2/topics/serialization/

Simpler issue I believe:

 return JsonResponse(json.dumps(sorted_venues))

is redundant, this should work:

return JsonResponse(sorted_venues)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM