我有以下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')
我在这里做错了什么
答案 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)