我有一個像這樣的簡單模型:
class Place(models.Model):
location = LocationField(
map_attrs={"style": "mapbox://styles/mightysharky/cjwgnjzr004bu1dnpw8kzxa72", "center": (17.031645, 51.106715)})
latitude = models.FloatField(blank=True, null=True)
longitude = models.FloatField(blank=True, null=True)
location 欄位使用 mapbox api 獲取選定位置的緯度和經度。當提交時,它會像這樣保存: location = (43.12,54,12) 我想拆分這個輸出并將其保存到緯度和經度欄位中。我如何撰寫一個 pre_save 方法來做到這一點?
********* 更新 ********* 我寫了這個 pre_save 信號,但它不起作用:
@receiver(pre_save)
def pre_save_software_reciever(sender, instance, *args, **kwargs):
instance.location = "{},{}".format(instance.latitude, instance.longitude)
pre_save.connect(pre_save_software_reciever, sender=Place)
uj5u.com熱心網友回復:
1 IF 位置是一個SET,
class Place(models.Model):
location = LocationField(
map_attrs={"style": "mapbox://styles/mightysharky/cjwgnjzr004bu1dnpw8kzxa72", "center": (17.031645, 51.106715)})
latitude = models.FloatField(blank=True, null=True)
longitude = models.FloatField(blank=True, null=True)
def save(self, *args, **kwargs):
#Directly access tuple values
self.latitude = self.location[0]
self.longitude = self.location1[1]
super(Model, self).save(*args, **kwargs)
2如果 Location 是一個字串,
class Place(models.Model):
location = LocationField(
map_attrs={"style": "mapbox://styles/mightysharky/cjwgnjzr004bu1dnpw8kzxa72", "center": (17.031645, 51.106715)})
latitude = models.FloatField(blank=True, null=True)
longitude = models.FloatField(blank=True, null=True)
def save(self, *args, **kwargs):
#manipulate the string to extract lat and long...
location_coordinates = self.location.split(',')
self.latitude = float(location_coordinates[0][1:])
self.longitude = float(location_coordinates[1][:-1])
super(Model, self).save(*args, **kwargs)
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/343435.html
標籤:姜戈
上一篇:使DjangoORM自動獲取屬性
