django-model-utils icon indicating copy to clipboard operation
django-model-utils copied to clipboard

Incorrect FieldTracker behaviour if primary key is not AutoField

Open MaximZemskov opened this issue 4 years ago • 1 comments

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

MaximZemskov avatar Jul 27 '20 16:07 MaximZemskov

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

MRigal avatar Oct 07 '21 09:10 MRigal