Temporarily disable auto_now / auto_now_add Temporarily disable auto_now / auto_now_add django django

Temporarily disable auto_now / auto_now_add


I've recently faced this situation while testing my application. I needed to "force" an expired timestamp. In my case I did the trick by using a queryset update. Like this:

# my modelclass FooBar(models.Model):    title = models.CharField(max_length=255)    updated_at = models.DateTimeField(auto_now=True, auto_now_add=True)# my testsfoo = FooBar.objects.get(pk=1)# force a timestamplastweek = datetime.datetime.now() - datetime.timedelta(days=7)FooBar.objects.filter(pk=foo.pk).update(updated_at=lastweek)# do the testing.


You can't really disable auto_now/auto_now_add in another way than you already do. If you need the flexibility to change those values, auto_now/auto_now_add is not best choice. It is often more flexible to use default and/or override the save() method to do manipulation right before the object is saved.

Using default and an overridden save() method, one way to solve your problem would be to define your model like this:

class FooBar(models.Model):    createtime = models.DateTimeField(default=datetime.datetime.now)    lastupdatetime = models.DateTimeField()    def save(self, *args, **kwargs):        if not kwargs.pop('skip_lastupdatetime', False):            self.lastupdatetime = datetime.datetime.now()        super(FooBar, self).save(*args, **kwargs)

In your code, where you want to skip the automatic lastupdatetime change, just use

new_entry.save(skip_lastupdatetime=True)

If your object is saved in the admin interface or other places, save() will be called without the skip_lastupdatetime argument, and it will behave just as it did before with auto_now.


You can also use the update_fields parameter of save() and pass your auto_now fields. Here's an example:

# Date you want to forcenew_created_date = date(year=2019, month=1, day=1)# The `created` field is `auto_now` in your modelinstance.created = new_created_dateinstance.save(update_fields=['created'])

Here's the explanation from Django's documentation: https://docs.djangoproject.com/en/stable/ref/models/instances/#specifying-which-fields-to-save