custom save method on model - django

AlexBrand picture AlexBrand · Jul 12, 2012 · Viewed 12k times · Source

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?

Answer

jagm picture jagm · Jul 12, 2012
def save(self, *args, **kwargs):
    if not self.pk:
        self.set_coords()
    super(Post, self).save(*args, **kwargs)