Skip to content

Instantly share code, notes, and snippets.

@nealtodd
Last active August 10, 2020 06:49
Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nealtodd/4594575 to your computer and use it in GitHub Desktop.
Save nealtodd/4594575 to your computer and use it in GitHub Desktop.
Django helper for showing related objects that would be cascade deleted on deletion of an object.
from django.conf import settings
from django.db.models.deletion import Collector
from django.db.utils import ConnectionRouter
def deletable_objects(obj):
"""
Return a generator that yields (model, instance) tuples
of instances related to obj (including obj itself).
Essentially, programmatic access to the data Django Admin
shows when asking 'are you sure' prior to deleting an
instance.
NB: m2m instances are not yielded by
Collector.instances_with_model() but the m2m data would be
deleted.
"""
router = ConnectionRouter(settings.DATABASE_ROUTERS)
using = router.db_for_write(obj.__class__)
collector = Collector(using)
collector.collect([obj])
return collector.instances_with_model()
# Example. Show all the unique models that have instances
# related to an instance.
from somewhere.models import MyModel
my_model = MyModel.objects.get(id=some_id)
unique_models = set()
for d in deletable_objects(my_model):
unique_models.add(d[0]._meta.object_name)
unique_models
@chexov
Copy link

chexov commented Aug 10, 2020

thanks

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment