Reputation: 99
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?
Upvotes: 2
Views: 566
Reputation: 11726
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.
Upvotes: 1
Reputation: 11523
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.
Upvotes: 0