简体   繁体   中英

Django rest framework, use none in model's field

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

elevation = models.FloatField...

fields = ('id', 'Name', 'Area', 'Latitude', 'Longitude', 'Elevation')

field names are case-sensitive, elevation != Elevation. Try using lowercase only.

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