Reputation: 595
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"
Upvotes: 1
Views: 10425
Reputation: 165
Simpler issue I believe:
return JsonResponse(json.dumps(sorted_venues))
is redundant, this should work:
return JsonResponse(sorted_venues)
Upvotes: 1
Reputation: 31555
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/
Upvotes: 3