[Django]-Django List objects that will be deleted by deleting the current object

7👍

You can do so doing

from django.contrib.admin.utils import NestedObjects
from django.db import DEFAULT_DB_ALIAS

collector = NestedObjects(using=DEFAULT_DB_ALIAS)
collector.collect([obj])
print(collector.nested())

0👍

You can filter the objects with that particular object_id. For example:

qs = Solution.objects.filter(exercise__book__course_id=course_id).select_related('exercise__book')

This will give a queryset of all the objects of Solution with related foreign key objects exercise and book. Then you can loop through this queryset and check instance._meta.app_label to differentiate between the objects.

0👍

Maybe this is a duplicated question with How can I check what objects will be cascade deleted in Django?. So I paste the same answer:

I suggest using the NestedObjects util provided in django admin.

from django.contrib.admin.utils import NestedObjects
from django.db import router

using = router.db_for_write(Item._meta.model)
# if you only have one database, just set using = "default"

nested_object = NestedObjects(using)
nested_object.collect([Item])
# If you want to delete multi item, you can use:
# nested_object.collect(Model.objects.filter(type="deleted"))

print(nested_object.nested()

The result look like this:
example result

👤ramwin

Leave a comment