Can multiple Django `bulk_update` queries be part of single atomic transaction?

Can multiple Django bulk_update queries be part of a single atomic transaction?

Usually when we want to save multiple models in single atomic transaction we can do something like this:

def my_update(model_a, model_b, model_c, model_d):
    with transaction.atomic():
        model_a.save()
        model_b.save()
        model_c.save()
        model_d.save()

Similarly I want to update a bulk set of models in single atomic transaction, like so:

def my_bulk_update(models_a, fields_a, models_b, fields_b, models_c, fields_c, models_d, fields_d):
    with transaction.atomic():
        Model_A.objects.bulk_update(objs=models_a, fields=fields_a)
        Model_B.objects.bulk_update(objs=models_b, fields=fields_b)
        Model_C.objects.bulk_update(objs=models_c, fields=fields_c)
        Model_D.objects.bulk_update(objs=models_d, fields=fields_d)

Digging around the bulk_update code I found the following snippet:

        with transaction.atomic(using=self.db, savepoint=False):
            for pks, update_kwargs in updates:
                rows_updated += self.filter(pk__in=pks).update(**update_kwargs)

It shows the updates are done within an atomic transaction. It means the my_bulk_update has nested atomic transaction and I'm not aware what the behaviour would be. So some queries I have regarding this are:

  1. Is my_bulk_update atomic?
  2. What is the behaviour of the nested transaction?
  3. Could the using=self.db mean that nested transactions be ignored?
Back to Top