开发者

Distinction between update and new entry in Django

开发者 https://www.devze.com 2023-03-18 00:27 出处:网络
I use the save() method to override the models.Model method in order to manipulate a bit of the properties before saving them in the DB (for example, issuing a Google MAPS API call to get geolocation

I use the save() method to override the models.Model method in order to manipulate a bit of the properties before saving them in the DB (for example, issuing a Google MAPS API call to get geolocation of an address).

However, I would not like to开发者_运维百科 issue a call to Google everytime I update an entry via the admin panel, but only when I insert a new entry.

Is there any easy way to do it (instead of running a query against the DB inside the save() method and check if the object already exists)?

Meir


check the primary key of that said object on save()

def save(self, *args, **kwargs):
    if self.pk:
        # this is executed when updating (pk exists)
    else:
        # this is executed when inserting
    super(Model, self).save(*args, **kwargs)

something like that

source

read the link thoroughly, theres a gotcha there

EDIT: gotchas, read the comments for more gotchas


https://docs.djangoproject.com/en/dev/ref/models/querysets/#get-or-create

basically, with this you can check if your object exists and run your update, or create a new one if the object isn't int your database

0

精彩评论

暂无评论...
验证码 换一张
取 消