Update Related Object Fields

 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. Duplicate related objects of model instance by johnboxall 3 years, 4 months ago
  2. Allow any view (probably a generic view) to accept POST variables into extra_context by orblivion 1 year, 6 months ago
  3. Owner required decorator by polarbear 3 years, 10 months ago
  4. Allow any view (probably a generic view) to accept captured URL variables into extra_context. by orblivion 1 year, 6 months ago
  5. FieldLevelPermissionsAdmin by buriy 4 years, 8 months ago

Comments

(Forgotten your password?)