问题
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