【问题标题】:Django rest framework, serializer method field doesn't save changes to db?Django rest框架,序列化方法字段不保存对db的更改?
【发布时间】:2020-07-22 23:04:44
【问题描述】:

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

【问题讨论】:

    标签: python django django-rest-framework


    【解决方案1】:

    Documentation 很清楚这一点 - SerializerMethodField只读

    我认为您需要的是custom fieldDjango Rest Framework How to update SerializerMethodField 是一个很好的起点。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-10-14
      • 1970-01-01
      • 2016-12-30
      • 1970-01-01
      • 1970-01-01
      • 2020-03-05
      • 2019-03-18
      • 2019-05-11
      相关资源
      最近更新 更多