Skip to content

Instantly share code, notes, and snippets.

@johnboxall
Created January 15, 2009 06:17
Show Gist options
  • Save johnboxall/47287 to your computer and use it in GitHub Desktop.
Save johnboxall/47287 to your computer and use it in GitHub Desktop.
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 delete object code of `CollectedObjects`:
http://code.djangoproject.com/browser/django/trunk/django/db/models/query.py
"""
# Collect all related objects.
collected_objs = CollectedObjects()
obj._collect_sub_objects(collected_objs)
classes = collected_objs.keys()
# Bulk update the objects for performance
for cls in classes:
items = collected_objs[cls].items()
pk_list = [pk for pk, instance in items]
cls._default_manager.filter(id__in=pk_list).update(**{field:value})
return obj
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment