0

I've got model, which has 'active' field, I'd like to do action if it's value has changed

class Good(TimeStampedModel):
    active = models.BooleanField(default=True)

    def save(self, **kwargs):
    #if self.active has changed:
    #do_something()
        super().save(self, **kwargs) 
Ernst
  • 514
  • 10
  • 26
  • 1
    Check this https://stackoverflow.com/questions/1355150/django-when-saving-how-can-you-check-if-a-field-has-changed – neverwalkaloner Feb 14 '18 at 14:36
  • Check this https://docs.djangoproject.com/en/2.0/ref/signals/ – Anup Yadav Feb 14 '18 at 14:38
  • 1
    @AnupYadav signals should not be used when you can do the job in the model itself. Actually the point of signals is to let _other applications_ hook into your own app without having to monkeypatch or fork it. – bruno desthuilliers Feb 14 '18 at 14:42
  • 1
    The solution mentionned in https://stackoverflow.com/q/1355150/41316 is fine but won't handle race conditions (ie if someone else already updated your record's `active` field in the meantime). Depending on what `do_something()` is actually about and how problematic it would be if it was executed twice, you may want to check against _both_ the original value (as in https://stackoverflow.com/q/1355150/41316 AND the current db value (reloading the model from db). – bruno desthuilliers Feb 14 '18 at 14:49

1 Answers1

0

If this suits you, there is a FieldTracker utility on django-model-utils: django-model-utils docs. You can check the current value against the previous value of the field that you want to track.

Andrei Todo
  • 39
  • 1
  • 3