从浮点数到字符串的转换覆盖保存方法

编程入门 行业动态 更新时间:2024-10-24 22:17:32
本文介绍了从浮点数到字符串的转换覆盖保存方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我正在使用 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)

更多推荐

从浮点数到字符串的转换覆盖保存方法

本文发布于:2023-08-01 08:53:59,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1267020.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:浮点   字符串   数到   方法

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!