从浮点数到字符串的转换覆盖保存方法 [英] Overwrite save method with conversion from float to string
问题描述
我正在使用 django-mapbox-location-field 和我需要将数据从LocationField()
自动保存到另一个名为coordinates
的字段中.
I'm using django-mapbox-location-field and I need to save automatically the data from LocationField()
into another field named coordinates
.
这是我的模特
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:
无法将字符串转换为浮点型: '1.110756623730225,17.0771352648959'
could not convert string to float: '1.110756623730225,17.0771352648959'
我不明白为什么会这样.在save方法中,float会转换为字符串,而不是反之,坐标是一个char字段.
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.
推荐答案
感谢@Patrick Artner的表示,我已经解决了问题.
Thanks to indication of @Patrick Artner I've solved the problem.
解决方案是这样的:
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)
这篇关于从浮点数到字符串的转换覆盖保存方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!