Overwrite save method with conversion from float to string

左心房为你撑大大i 提交于 2019-12-25 01:24:23

问题


I'm using django-mapbox-location-field and I need to save automatically the data from LocationField() into another field named coordinates.

This is my model:

class AddPoint(models.Model):
    point = LocationField()
    coordinates = models.CharField(
        max_length=50,
        blank=True,
        null=True,
    )

    def save(self, *args, **kwargs):
        lat = self.point[0]
        lon = self.point[1]
        lon_lat = str(lon) + ', ' + str(lat)
        self.coordinates = lon_lat
        super(AddPoint, self).save(*args, **kwargs)

Everytime I try to add a point in admin panel I see this error:

could not convert string to float: '1.110756623730225,17.0771352648959'

I don't understand why happen this. In the save method float is converted to string and not viceversa, moreover coordinates is a char field.


回答1:


Thanks to indication of @Patrick Artner I've solved the problem.

The solution is this:

def save(self, *args, **kwargs):
    lat = self.point[0]
    lon = self.point[1]
    lon_lat = str(str(lon) + ', ' + str(lat))
    self.coordinates = lon_lat
    super(AddPoint, self).save(*args, **kwargs)


来源:https://stackoverflow.com/questions/58353037/overwrite-save-method-with-conversion-from-float-to-string

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!