Updating an object and all related objects in Django - `update_related_field`

In one of our Django projects we needed to transfer ownership of an object and all it’s related objects from one user to another. A solution might look something like this:

  1. Collect all related objects related to the object you want to transfer.
  2. Update the ownership field on all the related objects.
  3. Save all the related objects!

django.db.models.query has a class CollectedObjects that makes this a snap. CollectedObjects works with Model._collect_sub_objects to find all related classes and objects of the object you want to transfer. Then you can use the update queryset method on each different class of the related objects to set them to their new owner. Here is a function update_related_field:

And here it is customized to update the owner property of an object:

Leave a Reply