Created
January 15, 2009 06:17
-
-
Save johnboxall/47287 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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