I am overriding the save method on one of my models:
def save(self, *args, **kwargs):
self.set_coords()
super(Post, self).save(*args, **kwargs)
def __unicode__(self):
return self.address
# set coordinates
def set_coords(self):
toFind = self.address + ', ' + self.city + ', ' + \
self.province + ', ' + self.postal
(place, location) = g.geocode(toFind)
self.lat = location[0]
self.lng = location[1]
However, I only want to run set_coords()
once, when the post is being created. This function should not run when the model is being updated.
How can I accomplish this? Is there any way of detecting if the model is being created or updated?
Creating objects To create an object, instantiate it using keyword arguments to the model class, then call save() to save it to the database. This performs an INSERT SQL statement behind the scenes. Django doesn't hit the database until you explicitly call save() . The save() method has no return value.
save() method from its parent class is to be overridden so we use super keyword. slugify is a function that converts any string into a slug. so we are converting the title to form a slug basically. Let us try to create an instance with “Gfg is the best website”.
str function in a django model returns a string that is exactly rendered as the display name of instances for that model.
def save(self, *args, **kwargs):
if not self.pk:
self.set_coords()
super(Post, self).save(*args, **kwargs)
I think the correct way to do it is using post_save signal:
def set_coords(sender, **kw):
model_instance = kw["instance"]
if kw["created"]:
toFind = model_instance.address + ', ' + model_instance.city + ', ' + \
model_instance.province + ', ' + model_instance.postal
(place, location) = g.geocode(toFind)
model_instance.lat = location[0]
model_instance.lng = location[1]
model_instance.save()
post_save.connect(set_coords, sender=MyModel)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With