django-model-utils
django-model-utils copied to clipboard
Incorrect FieldTracker behaviour if primary key is not AutoField
Problem
In cases when primary key is not AutoField
(e.g. UUIDField
) FieldTracker
has different behaviour
Environment
- Django Model Utils version: 4.0.0
- Django version: 2.2.13
- Python version: 3.8
Code examples
Correct behaviour:
Model
class Test(models.Model):
t_field = models.CharField(max_length=120)
tracker = FieldTracker(fields=('t_field',))
Input:
t = Test(t_field='test')
print(t.tracker.changed())
Output:
>>> {'t_field': None}
Incorrect behaviour
Model
class Test(models.Model):
id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
t_field = models.CharField(max_length=120)
tracker = FieldTracker(fields=('t_field',))
Input:
t = Test(t_field='test')
print(t.tracker.changed())
Output:
>>> {}
Seem like fix is very easy. Just replace if not self.instance.pk
check with if self.instance._state.adding
in https://github.com/jazzband/django-model-utils/blob/master/model_utils/tracker.py#L104
As seen in the failing tests in the PR, this is not working with defferred fields, so the fix isn't so easy. Anyone can try to fix it in the open PR