You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
There is a problem with Models which have primary key with default=uuid
id = models.UUIDField(default=uuid.uuid4, editable=False, primary_key=True)
The initial/first field history value is not saved to database.
It is caused by is_new_object = instance.pk is None in tracker.py
This approach has a problem:
In the save method, self.pk will never be None when default=uuid.uuid is set.
A large number of django users (and a lot of non-official django tutorials) believe that checking self.pk in the save method is a safe way to detect and decide whether an instance of a model is new or not.
So I think you should switch from is_new_object = instance.pk is None
to is_new_object = instance._state.adding
The text was updated successfully, but these errors were encountered:
Kub-AT
changed the title
Problematic is_new_object based on primary key when using default uuid
Problematic is_new_object based on primary key with default uuid
Sep 17, 2021
Hi.
There is a problem with Models which have primary key with default=uuid
The initial/first field history value is not saved to database.
It is caused by
is_new_object = instance.pk is None
in tracker.pyThis approach has a problem:
In the save method, self.pk will never be None when default=uuid.uuid is set.
A large number of django users (and a lot of non-official django tutorials) believe that checking self.pk in the save method is a safe way to detect and decide whether an instance of a model is new or not.
No its not. The safe way to detect and decide whether an instance of a model is new or not is to use self._state object
https://docs.djangoproject.com/en/3.2/ref/models/instances/#state
So I think you should switch from
is_new_object = instance.pk is None
to
is_new_object = instance._state.adding
The text was updated successfully, but these errors were encountered: