简体   繁体   中英

keyerror in drf serializer

I have a serializer like this :

class LocationSerializer(serializers.Serializer):
    
    lat = serializers.DecimalField(max_digits=9, decimal_places=6),
    lng = serializers.DecimalField(max_digits=9, decimal_places=6),
    term = serializers.CharField(max_length=100)

in views.py :

@api_view(['POST'])
def get_prefer_locations(request):        
    serilizer = LocationSerializer(data=request.data)
    if serilizer.is_valid():
        print(request.data)
        location_obj=Location(serilizer.data['lat'],serilizer.data['lng'],serilizer.data['term'])
        address = location_obj.convert_latandlong_to_address()

and this is the Location class that i have defined :

class Location:
    def __init__(self, latitude,longitude,term):
        self.lat = latitude,
        self.lng=longitude,
        self.term=term
        
    def convert_latandlong_to_address(self):

        geolocator = Nominatim(user_agent="geoapiExercises")
        location = geolocator.reverse(self.lat+","+self.lng)
        address = location.raw['address']
        return address

when i printed request.data in terminal i got this :

{'lat': '29.623411959216355', 'lng': '52.49860312690429', 'term': 'cafe'}

but i got this error :

  File "/home/admin1/mizbanproject/location/preferlocation/api/views.py", line 15, in get_prefer_locations
    location_obj = Location(serilizer.data['lat'],serilizer.data['lng'],serilizer.data['term'])
KeyError: 'lat'

and this is the json i am sending via postman:

{
    "lat":"29.623411959216355",
    "lng":"52.49860312690429",
    "term":"cafe"
}

由于您正在验证您的序列化程序,验证数据应该可以在validated_data访问:

location_obj=Location(serilizer.validated_data['lat'],serilizer.validated_data['lng'],serilizer.validated_data['term'])

I changed the serilizers to below and it works the problem was in max_digits and decimal_places :

class LocationSerializer(serializers.Serializer):

    lat = serializers.DecimalField(max_digits=25,decimal_places=15)
    lng = serializers.DecimalField(max_digits=25, decimal_places=15)
    term = serializers.CharField(max_length=100)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM