[英]Django Model is not JSON serializable
我试图以 JSON 格式返回 Django 模型的字典。
我尝试过序列化程序、model_to_dict、json.dump,但似乎无法正常工作。
一小段代码:
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))
我创建的字典是一个 {int:object, int:object, int:object, ....}
我希望将其作为响应返回。 我不断收到诸如“类型错误:对象类型的对象不是 JSON 可序列化的”之类的问题
使用django.core.serializers
:
from django.core import serializers
qs = YourModel.objects.filter(foo='bar')
serialized_qs = serializers.serialize('json', qs)
print(serialized_qs)
文档: https : //docs.djangoproject.com/en/2.2/topics/serialization/
我相信更简单的问题:
return JsonResponse(json.dumps(sorted_venues))
是多余的,这应该有效:
return JsonResponse(sorted_venues)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.