1

I've the following get_or_create method.

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)

This works fine for creating a new location, However if the location exists, I get the following error,

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

This is my model serializer,

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

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

What am I doing wrong here

Melissa Stewart
  • 3,483
  • 11
  • 49
  • 88

2 Answers2

1

For some reason you have bypassed all the logic that DRF does for you, so that you never use your serializer; you are passing your Location object directly to the JSON response in the try block.

Instead of doing that, you should instantiate your serializer from the model instance object, then pass that serializer data to the response, like you do in the except block.

Daniel Roseman
  • 588,541
  • 66
  • 880
  • 895
-1

JSON dumps only works with basic types (str, int, float, bool, None). You're trying to dump an object, which is not 'dump-able'. Convert the object to a dictionary, as for example:

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)
Renato Byrro
  • 3,578
  • 19
  • 34