djangodjango-models

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


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?


Solution

  • Updated: With the clarification that self._state is not a private instance variable, but named that way to avoid conflicts, checking self._state.adding is now the preferable way to check.


    self.pk is None:
    

    returns True within a new Model object, unless the object has a UUIDField as its primary_key.

    The corner case you might have to worry about is whether there are uniqueness constraints 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.