3👍
✅
Use a custom save method to update the field by looking at a previous instance.
from django.db import models
from django.utils import timezone as tz
class MyModel(models.Model):
name = models.CharField(max_length=255)
modify_time = models.DateTimeField(null=True, blank=True)
chasha = models.CharField(max_length=255)
stat = models.CharField(max_length=255)
def save(self, *args, **kwargs):
if self.pk: # object already exists in db
old_model = MyModel.objects.get(pk=self.pk)
for i in ('name', 'chasha'): # check for name or chasha changes
if getattr(old_model, i, None) != getattr(self, i, None):
self.modify_time = tz.now() # assign modify_time
else:
self.modify_time = tz.now() # if new save, write modify_time
super(MyModel, self).save(*args, **kwargs) # call the inherited save method
Edit: remove auto_now
from modify_time
like above, otherwise it will be set at the save method.
Source:stackexchange.com