返回json响应而不是Django模型列表

2024-04-16 11:53:30 发布

您现在位置:Python中文网/ 问答频道 /正文

我是python和Django的新手,这是我的第一个项目。我遵循了一个教程,其中返回了一个对象列表。我想返回json。你知道吗

我试过JsonResponse,json.dump文件但我不认为我实施这些权利

class ListVenuesView(generics.ListAPIView):

    serializer_class = VenueSerialiser

    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] = model_to_dict(venue)
        sorted_venues = dict(sorted(venue_gaps.items()))
        #print(sorted_venues)
        jsonResponse = json.dumps(venue_gaps, sort_keys=True)
        print(jsonResponse)

        return JsonResponse({'data':jsonResponse}, safe=False)

当前抛出

Got AttributeError when attempting to get a value for field `name` on serializer `VenueSerialiser`.

如果我把回流管换成

return Venue.objects.all()

我有200,但我需要json格式的

class VenueSerialiser(serializers.ModelSerializer):
    class Meta:
        model = Venue
        fields = ('name', 'location', 'capacity', 'photo_url', 'accomodation', 'cost', 'description', 'postcode', 'email', 'website')

Tags: jsonforgetlocationclassdistancequerysetsplit