对象类型' A'不是JSON可序列化的

时间:2018-03-16 17:16:26

标签: python django python-3.x django-rest-framework

我有以下get_or_create方法。

class LocationView(views.APIView):
    def get_or_create(self, request):
        try:
            location = Location.objects.get(country=request.data.get("country"), city=request.data.get("city"))
            print(location)
            return Response(location, status=status.HTTP_200_OK)
        except Location.DoesNotExist:
            serializer = LocationSerializer(data=request.data)
            if serializer.is_valid():
                serializer.save()
                return Response(serializer.data, status=status.HTTP_201_CREATED)
            else:
                return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)

    def get(self, request):
        return self.get_or_create(request)

    def post(self, request):
        return self.get_or_create(request)

这适用于创建新位置, 但是,如果该位置存在,我会收到以下错误,

TypeError: Object of type 'Location' is not JSON serializable
[16/Mar/2018 10:10:08] "POST /api/v1/bouncer/location/ HTTP/1.1" 500 96971

这是我的模型序列化程序,

class LocationSerializer(serializers.ModelSerializer):
    id = serializers.IntegerField(read_only=True)

    class Meta:
        model = models.Location
        fields = ('id', 'country', 'city', 'longitude', 'latitude')

我在这里做错了什么

2 个答案:

答案 0 :(得分:1)

出于某种原因,你绕过了DRF为你做的所有逻辑,所以你永远不会使用你的序列化器;您将Location对象直接传递给try块中的JSON响应。

您应该从模型实例对象中实例化序列化程序,然后将该序列化程序数据传递给响应,而不是像except块中那样。

答案 1 :(得分:-1)

JSON转储仅适用于基本类型(str,int,float,bool,None)。您正试图转储一个无法转储的对象'。将对象转换为字典,例如:

location_dict = {
    'id': location.id,
    'country': location.country,
    'city': location.city,
    'longitude': location.longitude,
    'latitude': location.latitude
}
return Response(location_dict, status=status.HTTP_200_OK)