【发布时间】:2019-12-27 01:41:23
【问题描述】:
我正在尝试以 JSON 格式返回 Django 模型的字典。
我尝试过序列化程序、model_to_dict、json.dump,但似乎无法正常工作。
代码的小sn-p:
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, ....}
我希望将其作为响应返回。我不断收到诸如“TypeError: Object of type object is not JSON serializable”之类的问题
【问题讨论】:
-
字典是 test_dict,我在第二行初始化它。这是我的第一个 python/django 项目,所以我对此很陌生。感谢观看
标签: python json django python-3.x