Django rest 框架,序列化程序方法字段不保存对数据库的更改?



我有一个DRF API,它包含一个正在序列化程序中设置的字段:

class KnownLocation(models.Model):
latitude = models.FloatField(name="Latitude",
verbose_name='Latitude',
unique=True, max_length=255, blank=False,
help_text="Enter the location's Latitude, first when extracting from Google Maps.",
)
longitude = models.FloatField(name="Longitude",
verbose_name="Longitude",
unique=True, max_length=255, blank=False,
help_text="Enter the location's Longitude, second when extracting from Google Maps.",
)
elevation = models.FloatField(name="elevation",
help_text="Enter the location's ~Sea Level~ elevation, or Leave empty for auto-fill "
"by me :). ",
verbose_name="Elevation in meters",
blank=True,
default=DEFAULT_VALUE
)

和序列化程序:

class KnownLocationSerializer(HyperlinkedModelSerializer):
date_added = DateTimeField(format="%d-%m-%Y", required=False, read_only=True)
elevation = SerializerMethodField()
def validate_elevation(self, value):
"""
Validate that elevation of location has been updated already.
"""
if value is None or 1:
raise APIException.elevation.throw()
return value
def get_elevation(self, obj):
"""
This method, which is connected to SerializerMethodField, checks if the object's elevation value exists,
if not, it fetches it.
"""
elevation = obj.elevation
if elevation is None or 1:
elevation = get_elevation(lat=obj.Latitude, lon=obj.Longitude)
elevation = round(elevation)
return elevation
pass

该方法可以工作并获取高程,但它不会将其保存到数据库中。我错过了文档中的那个部分吗?那么,我如何将其保存到数据库中,使用保存对我不起作用:

def save(self, **kwargs):
latitude, longitude = self.instance.latitude, self.instance.longitude
self.instance.elevation = get_elevation(latitude, longitude)
self.instance.save()
return self.instance
def validate_elevation(self, value):
"""
Validate that elevation of location has been updated already.
"""
if value is None or 1:
raise APIException.elevation.throw()
return value

文档对此很清楚-SerializerMethodField是只读的。

我认为,你需要的是一个自定义字段。Django Rest Framework如何更新SerializerMethodField是一个很好的起点。

最新更新