2

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?

mikhdm
  • 109
  • 2
  • 12
  • 2
    I thing that pre_save or save or post_save are best solution for this issue. If i make it, i will implement save method of model. (Sorry for bad english) – simopopov Nov 29 '14 at 16:41
  • 2
    You can override `model.save` method and change `DateTime` field to `now`. http://stackoverflow.com/questions/4269605/django-override-save-for-model – Nilesh Nov 29 '14 at 16:43
  • Thanks guys. It seems the most appropriate solution for my case. – mikhdm Nov 29 '14 at 16:53

2 Answers2

1

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.

Mounir
  • 11,306
  • 2
  • 27
  • 34
0

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.
Alejandro Veintimilla
  • 10,743
  • 23
  • 91
  • 180