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

MonitorField value when the instance is created

Open alb3rto269 opened this issue 6 years ago • 0 comments

Problem

MonitoField works without issues when the instance is updated. However, when an instance is created the value is not set.

e.g.

class MyModel(StatusModel):
    STATUS = Choices('in_progress', 'success', 'error')

    finished = MonitorField(
        monitor='status',
        when=['success', 'error',],
        null=True,
        blank=True,
        default=None,
    )

Then,

obj = MyModel.objects.create(status=MyModel.STATUS.in_progress)
print obj.finished                # None    ---> OK

obj.status = MyModel.STATUS.error
obj.save()
print obj.finished                # `now()`    ---> OK

obj2 = MyModel.objects.create(status=MyModel.STATUS.error)
print obj2.finished                # None    ---> Wrong

I tracked the error to the pre_save method, which is not considering the add argument. Instead of checking if previous != current: it should be if add or previous != current:

The bug was introduced in this commit when StatusModifiedField was migrated to MonitorField. Notice that the _previous_status method used to check the add argument to force the field to act.

alb3rto269 avatar Nov 30 '18 12:11 alb3rto269