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?
For a solution that also works even when you have a
UUIDField
as a primary key (which as others have noted isn'tNone
if you just overridesave
), you can plug into Django's post_save signal. Add this to your models.py:This callback will block the
save
method, so you can do things like trigger notifications or update the model further before your response is sent back over the wire, whether you're using forms or the Django REST framework for AJAX calls. Of course, use responsibly and offload heavy tasks to a job queue instead of keeping your users waiting :)Alternative way to checking
self.pk
we can checkself._state
of the modelself._state.adding is True
creatingself._state.adding is False
updatingI got it from this page
I'm very late to this conversation, but I ran into a problem with the self.pk being populated when it has a default value associated with it.
The way I got around this is adding a date_created field to the model
date_created = models.DateTimeField(auto_now_add=True)
From here you can go
created = self.date_created is None
To know whether you are updating or inserting the object (data), use
self.instance.fieldname
in your form. Define a clean function in your form and check whether the current value entry is same as the previous, if not then you are updating it.self.instance
andself.instance.fieldname
compare with the new valuerather use pk instead of id:
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.