I have a simple model like this:
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)
the location field gets a latitude,longitude of a selected loction using a mapbox api. when, submitted, it gets saved like this: location = (43.12,54,12) I want to split this output and save it into latitude and longitude field. how do I write a pre_save method in order to do this?
********* UPDATE ********* I wrote this pre_save signal but its not working:
@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)
CodePudding user response:
1 IF Location is a 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 If Location is a string ,
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)