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()
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.
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.
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()
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:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With