Reputation:
I have a Django rest framework API, In one of the models, there is a field for GeoLocation's elevation, which defaults its value to None.
The reason for that is that it can be passed in by the user or if left empty, obtained by a call to google's elevation API.
So, I'm trying to use the create function in the serializer to define its value but I'm getting a key error:
#app/models.py
elevation = models.FloatField(name="Elevation",
max_length=255,
help_text="If known, Add location's sea level height. If not, Leave Empty.",
null=False,
default=None)
#app/serializers.py
from rest_framework.serializers import HyperlinkedModelSerializer
from Project_Level.utils import get_elevation
from .models import KnownLocation
class KnownLocationSerializer(HyperlinkedModelSerializer):
def create(self, validated_data):
if validated_data["Elevation"] is None: # Using if not validated_data["Elevation"] results the same.
validated_data["Elevation"] = get_elevation(validated_data["Latitude"], validated_data["Longitude"])
class Meta:
model = KnownLocation
fields = ('id', 'Name', 'Area', 'Latitude', 'Longitude', 'Elevation')
Error:
KeyError at /knownlocations/
'Elevation'
Exception Location: KnownLocation/serializers.py in create, line 9
Upvotes: 0
Views: 177
Reputation: 743
elevation = models.FloatField...
fields = ('id', 'Name', 'Area', 'Latitude', 'Longitude', 'Elevation')
field names are case-sensitive, elevation != Elevation. Try using lowercase only.
Upvotes: 0