模型上的自定义保存方法-django [英] custom save method on model - django

查看:239
本文介绍了模型上的自定义保存方法-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)

这篇关于模型上的自定义保存方法-django的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆