gpt4 book ai didi

python - Django 模型不可 JSON 序列化

转载 作者:行者123 更新时间:2023-12-01 00:38:03 26 4
gpt4 key购买 nike

我正在尝试返回 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, ....}

我希望将此作为响应返回。我不断收到诸如“TypeError:对象类型对象不可 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/

关于python - Django 模型不可 JSON 序列化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57597348/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com