Search code examples
djangodjango-modelsdjango-orm

How to bulk_update in related fields modified using only one call


I'm working with two tables to change some data in there but I'm wanted to avoid two calls using bulk_update as following:

queryset = MyModel.objects.all()
submodels_to_update = []
for instance in queryset:
    instance.submodel = process()
    instance.submodel.sub_property = some_random_data()
    submodels_to_update.append(instance.submodel)

MyModel.objects.bulk_update(queryset, ['submodel'])
SubModel.objects.bulk_update(submodels_to_update, ['sub_property'])

What I wanted to do is something like the following:

MyModel.objects.bulk_update(queryset, ['submodel', 'submodel__sub_property'])

But bulk_update seems like not support related_fields using the ORM syntax. My question here is if there is a way to achieve bulk_update in two different tables at the same time.

If the answer is that it is not possible I don't have any problem to accept that, just share the relevant links that prove that the approach that I'm describing here is not supported.


Solution

  • As it is documented here

    This method efficiently updates the given fields on the provided model instances, generally with one query, and returns the number of objects updated.

    Notice: updates the given fields on the provided model instances It can only update fields on the provided model instances. As @jerch pointed out

    The update() method is applied instantly, and the only restriction on the QuerySet that is updated is that it can only update columns in the model’s main table, not on related models." Internally bulk_update uses update method and that's why the restriction.