grantmcconnaughey / django-field-history

A Django app to track changes to model fields.
BSD 3-Clause "New" or "Revised" License
314 stars 33 forks source link

Problematic is_new_object based on primary key with default uuid #38

Open Kub-AT opened 3 years ago

Kub-AT commented 3 years ago

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