INSERT or UPDATE in django’s save() method
January 5, 2010 | frameworks, pythonauthor: Karol Zielinski | comments: 4 | views: 3353
Tags: django, insert, model, save, update
Django uses save() method in models to save all kind of data into database. This method is used by framework when you want to add or edit data. That’s great, however sometimes we need to know is it INSERT, or maybe UPDATE. How to check it?
Answer is really simple: by checking primary key.
From django’s documentation:
Specifically, when you call save(), Django follows this algorithm:
- If the object’s primary key attribute is set to a value that evaluates to True (i.e., a value other than None or the empty string), Django executes a SELECT query to determine whether a record with the given primary key already exists.
- If the record with the given primary key does already exist, Django executes an UPDATE query.
- If the object’s primary key attribute is not set, or if it’s set but a record doesn’t exist, Django executes an INSERT.
So… we just need to check primary key.
My save() method looks like:
def save(self):
if not self.id:
# what I want to do if it's INSERT statement
else:
# what I want to do if it's UPDATE statement
super(MyObject, self).save()
Notice: “super(MyObject, self).save()” has to be called after checking is it INSERT or UPDATE.
Hello, I'm Karol Zielinski, internet evangelist, an entrepreneur, project manager and a web developer from Gdynia, Poland. I like creative design, good advertisement, social media and all kind of stuff around the web.
January 5, 2010, 5:35 am
[...] tech.karolzielinski.com Follow us on Twitter 1,509 śledzących RSS Feed 164 czytelników INSERT / UPDATE w djangowym save()? 1 głosuj! Jak rozpoznać, czy metoda save() w djangowym modelu wywołana została w celu [...]
January 5, 2010, 6:27 am
I would suggest adding *args, and **kwargs to your function definition, and passing them in the call to the super-class’s save:
http://code.djangoproject.com/browser/django/trunk/django/db/models/base.py#L420
January 5, 2010, 8:23 am
Also note you can force an insert or an update with `model.save(force_insert=True)` or `force_update=true` (see http://docs.djangoproject.com/en/1.1/ref/models/instances/#forcing-an-insert-or-update for more details).
January 6, 2010, 3:46 am
Sure, you can. However… only if you call save() method by hand. If it’s used by admin panel – you can’t force any parameters.
I had a problem: I wanted to add information about new articles (added from admin panel) to twitter (automatic adding). I wanted to add it only if it’s new item (and not to add information to twitter if it’s edit).
So… I had to check it inside the method.