In a django model custom save() method, how should you identify a new object

djangodjango-models

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?

Best Answer

Alternative way to checking self.pk we can check self._state of the model

self._state.adding is True creating

self._state.adding is False updating

I got it from this page

Related Topic