Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Problematic is_new_object based on primary key with default uuid #38

Open
Kub-AT opened this issue Sep 17, 2021 · 0 comments
Open

Problematic is_new_object based on primary key with default uuid #38

Kub-AT opened this issue Sep 17, 2021 · 0 comments

Comments

@Kub-AT
Copy link

Kub-AT commented Sep 17, 2021

Hi.

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.

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

@Kub-AT 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
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant