Update auto_now field in bulk_update

3.5k views Asked by At

I'm using Django 2.2 and I have a model with auto_now modification_datetime field and I need to update it during/after a bulk_update execution only for the affected registries that were really updated.

Is it possible to update auto_now datetime model field only on the affected records by bulk_update execution?

2

There are 2 answers

0
iklinac On BEST ANSWER

No as bulk_update() does not call save() method nor it fires pre_save and post_save signals on instance ( generally produces only single update query). Also generally there is no recollection of the instances that are actually updated in Django

furthermore as documented auto_now does not trigger on update()/bulk_update() as it is triggered by save()

The field is only automatically updated when calling Model.save(). The field isn’t updated when making updates to other fields in other ways such as QuerySet.update(), though you can specify a custom value for the field in an update like that.

You could check which instances have update manually and update their timestamp or do some kind of database trigger

0
Schulzjo On

Maybe override your update method in QuerySet helps. But I am not sure if this only updates "updated_at" on data which have really changed in bulk update.

from django.db import models
from django.utils import timezone

class YourModelQuerySet(models.QuerySet):

    def update(self, **kwargs):
        kwargs['updated_at'] = timezone.now()
        super().update(**kwargs)

class YourModel(models.Model):
    objects = YourModelQuerySet.as_manager()

    updated_at = models.DateTimeField()
    other_fields = ...

Edit:

look also here: https://brobin.me/blog/2020/02/auto-updated-timestamp-fields-in-django-bulk-querysets/