How to know if an object is being created in the save() method?

97 views
Skip to first unread message

Julien

unread,
Jan 30, 2008, 10:44:04 PM1/30/08
to Django users
Hello there,

Does the title says it all? When overriding the save method of an
object, I'd like to know if that object is being created or updated.

How I do it so far is:

def save(self):
if self.pk:
...=> being created
else:
...=> being updated

I vaguely remember seeing a parameter for the save method which would
do that, but I can't find it. Any thoughts?

Thanks!

Julien

Ivan Illarionov

unread,
Jan 30, 2008, 11:22:43 PM1/30/08
to Django users
There is 'post_save' signal with 'created' parameter. But,
unfortunately, this feature is undocumented...

Eren Türkay

unread,
Jan 31, 2008, 12:48:25 AM1/31/08
to django...@googlegroups.com
On 31 Jan 2008 Thu 06:22:43 Ivan Illarionov wrote:
> There is 'post_save' signal with 'created' parameter. But,
> unfortunately, this feature is undocumented...

It's something related with "dispatcher" class? Please let me know if there is
more about signals than the code below. I simply just use this;

-----
...
...
from django.db.models import signals
from django.dispatch import dispatcher
from myapp.signal_handlers import do_something_before_adding

class FooModel(models.Model)
.....
.....

dispatcher.connect(do_something_before_adding, signal=signals.pre_save,
sender=FooModel)

-----

This code will call "do_something_before_adding" before the object is created.
I don't know what parameters are appended to function, but just do triald and
error :) I hope, this will help you Julien.

Btw, in the "django.db.models.signals", these signals exist;

class_prepared
pre_init
pot_init
pre_save
post_save
pre_delete
post_delete
post_syncdb

Michael Elsdörfer

unread,
Jan 31, 2008, 1:20:07 AM1/31/08
to django...@googlegroups.com
>> There is 'post_save' signal with 'created' parameter. But,
>> unfortunately, this feature is undocumented...
>
> It's something related with "dispatcher" class? Please let me know if
> there is more about signals than the code below. I simply just use
> this;

If you use post_save instead of pre_save, your signal handler is passed
a 'created' flag.

Michael

Michael Elsdörfer

unread,
Jan 31, 2008, 1:21:37 AM1/31/08
to django...@googlegroups.com
> def save(self): if self.pk: ...=> being created else: ...=> being
> updated
>
> I vaguely remember seeing a parameter for the save method which would
> do that, but I can't find it. Any thoughts?

That's the correct way to do it, unless you want to use signals:

http://www.martin-geber.com/weblog/2007/10/29/django-signals-vs-custom-save-method/

Michael

Ivan Illarionov

unread,
Jan 31, 2008, 1:37:50 AM1/31/08
to Django users
Example of post_save with 'created' flag is in Django tests:
http://code.djangoproject.com/browser/django/trunk/tests/modeltests/signals/models.py
Reply all
Reply to author
Forward
0 new messages