Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I check what objects will be cascade deleted in Django?

In the /admin/ section of Django you can choose to delete items.

If any related objects would be deleted along with your chosen object you get to see a list of affected objects before you confirm delete.

Can I check this in my own function programmatically?

I'd like to do something like

for item in Item.objects.all():
    if not deletion_would_also_delete_other_objects(item):
        item.delete()
like image 553
Bohr Avatar asked Nov 07 '14 18:11

Bohr


People also ask

What is On_delete Cascade?

Use the ON DELETE CASCADE option to specify whether you want rows deleted in a child table when corresponding rows are deleted in the parent table. If you do not specify cascading deletes, the default behavior of the database server prevents you from deleting data in a table if other tables reference it.

What is soft delete in Django?

This is a set of small classes to make soft deletion of objects. Use the abstract model SoftDeleteModel for adding two new fields: is_deleted - is a boolean field, shows weather of a deletion state of object.


2 Answers

Could you use from django.db.models.deletion import Collector to do this?

from django.db.models.deletion import Collector
from .models import Item
  
for item in Item.objects.all(): 
    collector = Collector(using='default')
    collector.collect([item])

    # dependencies should be an empty dict if the item is not related to anything
    if not collector.dependencies:
        item.delete()
like image 92
Tareq Avatar answered Oct 17 '22 14:10

Tareq


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

like image 35
ramwin Avatar answered Oct 17 '22 14:10

ramwin