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

6uxekuva  于 2023-01-27  发布在  Go
关注(0)|答案(2)|浏览(125)

我在我的一个模型上重写保存方法:

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]

但是,我只想在创建post时运行set_coords()一次,在更新模型时不应该运行此函数。
我怎样才能做到这一点?有没有办法检测模型是否正在创建或更新?

zzoitvuj

zzoitvuj1#

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

y4ekin9u2#

我认为正确的方法是使用post_保存信号:

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)

相关问题