13

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

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()在创建帖子时运行一次。更新模型时不应运行此函数。

我怎样才能做到这一点?有什么方法可以检测模型是否正在创建或更新?

4

2 回答 2

33
def save(self, *args, **kwargs):
    if not self.pk:
        self.set_coords()
    super(Post, self).save(*args, **kwargs)
于 2012-07-12T17:05:40.513 回答
3

我认为正确的方法是使用 post_save 信号:

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)
于 2012-07-12T17:36:13.680 回答