Value of self._state.adding is incorrect when creating an object from existing one

Consider below code

class MyModel(models.Model):
    def save(self, *args, **kwargs):
        print("Before Save: ", self._state.adding)
        super().save(*args, **kwargs)
        print("After Save: ", self._state.adding)

If we run MyModel.objects.create(...), the output will be:

Before Save: True
After Save: False

However, if we set the primary key to None and call save() to create a new object, the value of self._state.adding remains the same:

mm1 = MyModel.objects.get(id=<id>)
mm1.pk = None
mm1.save()

it prints

Before Save: False
After Save: False

This issue does not occur when using the if not self.pk: approach.
But what would you suggest if self._state.adding is already being used throughout the project?

You should refer to the documentation on this subject; if you are copy’ing model instances it it your responsibility to set instance._state.adding accordingly.

1 Like