模型上的自定义保存方法-django

问题描述:

我在我的其中一个模型上覆盖了save方法:

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]

但是,创建帖子时,我只想运行一次set_coords().更新模型时,该功能不应运行.

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?

def save(self, *args, **kwargs):
    if not self.pk:
        self.set_coords()
    super(Post, self).save(*args, **kwargs)