Login

Update Related Object Fields

Author:
johnboxall
Posted:
December 22, 2008
Language:
Python
Version:
1.0
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. Template tag - list punctuation for a list of items by shapiromatron 3 months ago
  2. JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 3 months, 1 week ago
  3. Serializer factory with Django Rest Framework by julio 10 months, 1 week ago
  4. Image compression before saving the new model / work with JPG, PNG by Schleidens 10 months, 3 weeks ago
  5. Help text hyperlinks by sa2812 11 months, 3 weeks ago

Comments

Please login first before commenting.