簡體   English   中英

Django rest 框架,序列化方法字段不保存對數據庫的更改?

[英]Django rest framework, serializer method field doesn't save changes to db?

我有一個 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

該方法有效並獲取海拔高度,但它不會將其保存到數據庫中。 我錯過了文檔中的那部分嗎? 那么,如何將其保存到數據庫中,使用 save 對我不起作用:

    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是一個很好的起點。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM