jazzband / jazzband/django-model-utils

MonitorField value when the instance is created

Open
#352 0 comments 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

Dominant language
Python
Stars
2.8k
Forks
375
PR merge metrics
No merged PRs in 30d

Description

## 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](545bccf3ce63a29b0f29a1c620d88d72c3d873b8) when `StatusModifiedField` was migrated to `MonitorField`. Notice that the `_previous_status` method used to check the `add` argument to force the field to act.

Contributor guide

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Research direction

Start at MonitorField's pre_save method and inspect how it handles the add argument. Compare it with the _previous_status behavior from the StatusModifiedField migration commit; done means creating an instance in a monitored status sets the value to now() while preserving the existing update behavior.

Written by the indexing model from the issue text.

Assessment

Tech stack
django, python
Domain
backend
Issue type
Bug
Difficulty
2/5
Estimated time
1-3 hours
Activity status
Stale
Clarity
Clearly specified
Newbie friendliness
58/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.