views:

843

answers:

7

I want to trigger a special action in the save() method of a Django model object when I'm saving a new record (not updating an existing record.)

Is the check for (self.id != None) necessary and sufficient to guarantee the self record is new and not being updated? Any special cases this might overlook?

+7  A: 

Testing for

self.id is not None

will do the trick.

The corner case you might have to worry about is whether there are uniqueness constrains on fields other than the id (e.g., secondary unique indexes on other fields). In that case, you could still have a new record in hand, but be unable to save it.

Dave W. Smith
The corner case of save failure can be dealt with by wrapping the super() call in a try-except block and doing any necessary cleanup for the "special action".
Carl Meyer
You should use `is not` rather than `!=` when checking for identity with the `None` object
Ben James
Thanks Ben. Corrected above.
Dave W. Smith
+1  A: 

It is the common way to do so.

the id will be given while saved first time to the db

vikingosegundo
+5  A: 

Checking self.id assumes that id is the primary key for the model. A more generic way would be to use the pk shortcut.

is_new = self.pk is None

Gerry
+3  A: 

The check for self.pk == None is not sufficient to determine if the object is going to be inserted or updated in the database.

The Django O/RM features an especially nasty hack which is basically to check if there is something at the PK position and if so do an UPDATE, otherwise do an INSERT (this gets optimised to an INSERT if the PK is None).

The reason why it has to do this is because you are allowed to set the PK when an object is created. Although not common where you have a sequence column for the primary key, this doesn't hold for other types of primary key field.

If you really want to know you have to do what the O/RM does and look in the database.

Of course you have a specific case in your code and for that it is quite likely that self.pk == None tells you all you need to know, but it is not a general solution.

KayEss
Good point! I can get away with this in my application (checking for None primary key) because I never set the pk for new objects. But this would definitely not be a good check for a reusable plugin or part of the framework.
MikeN
A: 

rather use pk instead of id:

if not self.pk:
  do_something()
yedpodtrzitko
A: 

TO know whether u are updating or inserting the object(data)use self.instance.fieldname in ur form .define a clean functon in ur form and check whether the current value enter is same as that before ,if not then u r updateting it.

self.instance and self.instance.fieldname compare with the new value

ha22109
A: 

You could just connect to post_save signal which sends a "created" kwargs, if true, your object has been inserted. http://docs.djangoproject.com/en/1.2/ref/signals/#django.db.models.signals.post_save

JF Simon