django model field update on a special event

570 views Asked by At

If I define auto_now = True on a DateTimeField, than this field will be updated on every save(). But, how to update this field when something special happened?

For example: update DateTimeField only if some other field of the same Model has changed its state. Of course, I can define a trigger on a DB level, or catch pre_save or post_save signals to make stuff. But is there a way to do it another manner?

2

There are 2 answers

0
Mounir On

You can install django-models-utils and use it's MonitorField. It's a DateTimeField subclass that monitors another field on the model, and updates itself to the current date-time whenever the monitored field changes.

0
Alejandro Veintimilla On

You could use the 'update_fields' argument of the save() method:

# Write your logic to check if the fields or field has changed, then:
model.save(update_fields=['field1', 'field2'])  # Do not include the DateTimeField if you don't want it updated.