Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

custom save method on model - django

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?

like image 914
AlexBrand Avatar asked Jul 12 '12 17:07

AlexBrand


People also ask

How do I save models in Django?

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.

How do you override the Save method of a model?

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”.

What is __ str __ In Django model?

str function in a django model returns a string that is exactly rendered as the display name of instances for that model.


2 Answers

def save(self, *args, **kwargs):
    if not self.pk:
        self.set_coords()
    super(Post, self).save(*args, **kwargs)
like image 122
jagm Avatar answered Oct 21 '22 20:10

jagm


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)
like image 37
Abdeslem Daaif Avatar answered Oct 21 '22 18:10

Abdeslem Daaif