Login

Update Related Object Fields

Author:
johnboxall
Posted:
December 22, 2008
Language:
Python
Version:
1.0
Tags:
related update
Score:
1 (after 1 ratings)

Some times I want to change the owner of an object to another user - problem is the object often has a lot of other objects pointing to them - I also want to update those fields.

This is a generic snippet for doing just that!

For instance:

change_owner(obj, new_owner_id):
    return update_related_field(obj, new_owner_id, field="user")
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
from django.db.models.query import CollectedObjects

def update_related_field(obj, value, field):
    """
    Set `field` to `value` for all objects related to `obj`.
    Based on heavily off the delete object code:
    http://code.djangoproject.com/browser/django/trunk/django/db/models/query.py#L824
    """
    # Collect all related objects.
    related_objs = CollectedObjects()
    obj._collect_sub_objects(related_objs)
    classes = related_objs.keys()
    # Bulk update the objects for performance
    for cls in classes:
        items = related_objs[cls].items()
        pk_list = [pk for pk, instance in items]
        cls._default_manager.filter(id__in=pk_list).update(**{field:value})

More like this

  1. Create multiple related objects at once by yaniv.haber 6 years, 5 months ago
  2. duplicate model object merging script by nstrite 8 years ago
  3. Creator/updater fields for admin by baumer1122 7 years, 1 month ago
  4. RelatedMixin for Details and Updates with Related Object Lists by christhekeele 3 years, 3 months ago
  5. Duplicate related objects of model instance by johnboxall 6 years, 7 months ago

Comments

Please login first before commenting.