What is the most efficient way to make sure my updated_at
field- which has the auto_now
param not to be changed when the object remains the same on PATCH
request for example?
Asked
Active
Viewed 126 times
1

Medanko
- 708
- 1
- 7
- 16
-
Would you mind providing more context? – Siavoshkc Oct 27 '22 at 08:43
-
This [answer](https://stackoverflow.com/a/1793323/14457833) may help you – Ankit Tiwari Oct 27 '22 at 09:06
-
@AnkitTiwari Thanks for your comment. using this method I can see whether the object has changed or not, and then just skip the original save method in case nothing has changed. Im wondering if there's is a more generic and clean way to handle it. – Medanko Oct 27 '22 at 09:11
1 Answers
0
From the doc
Automatically set the field to now every time the object is saved. Useful for “last-modified” timestamps. Note that the current date is always used; it’s not just a default value that you can override.
The field is only automatically updated when calling Model.save().
So by implication, your code is invoking object.save()
even if nothing has been changed. You'll have to find a way to avoid this, or accept the unwanted auto-update.

nigel222
- 7,582
- 1
- 14
- 22
-
This is my question actually, what is the best way to avoid this ***without*** accepting the unwanted auto-update. – Medanko Oct 27 '22 at 09:05
-
Basically you need to find out where instance.save() is being called, and then put in place safeguards against it taking place if no change has been made. One general possibility might be to employ https://django-dirtyfields.readthedocs.io/en/stable/. If you know its caused by a form being POSTed with no changed fields, there's `form.has_changed` (but see https://stackoverflow.com/questions/44874486/cant-figure-out-why-form-has-changed-is-always-true) – nigel222 Oct 27 '22 at 13:57