Django model ON DELETE CASCADE, emulate ON DELETE RESTRICT instead, general solution

I would like to delete an instance of the model, but only if it does not have another instance of another class with a foreign key pointing to it. From the Django documentation:

When Django deletes an object, it emulates the behavior of the SQL ON DELETE CASCADE constraint — in other words, any objects that have foreign keys pointing to the deleted object will be deleted along with it.

In this example:

class TestA(models.Model)
    name = models.CharField()

class TestB(models.Model)
    name = models.CharField()
    TestAs = models.ManyToManyField(TestA)

# More classes with a ManyToMany relationship with TestA
# ........

I would like something like:

tA = TestA(name="testA1")
tB = TestB(name="testB1")
tB.testAs.add(tA)

t = TestA.objects.get(name="testA1")

if is_not_foreignkey(t):
    t.delete()
else:
    print "Error, some instance is using this"

Must print an error. I know that I can check specific instances that install sets of foreign keys, for example, in this case check t.TestB_set (), but I'm looking for a more general solution for any given model.

+3
3

, , Nullable ForeignKeys , :

    # Check foreign key references
    instances_to_be_deleted = CollectedObjects()
    object._collect_sub_objects(instances_to_be_deleted)

    # Count objects to delete
    count_instances_to_delete = 0
    for k in instances_to_be_deleted.unordered_keys():
        count_instances_to_delete += len(instances_to_be_deleted[k])

    if count_instances_to_delete == 1:
        object.delete()
    else:
        pass
+2

t=TestA.objects.get(name="textA1")
if not t.testB_set.all().count():#related members
  t.delete()
0

CollectedObjects () was removed in Django 1.3 - here is the current method:

from compiler.ast import flatten
from django.db import DEFAULT_DB_ALIAS
from django.contrib.admin.util import NestedObjects

def delete_obj_if_no_references(obj):
    collector = NestedObjects(using=DEFAULT_DB_ALIAS)
    collector.collect([obj])
    objs = flatten(collector.nested())
    if len(objs) == 1 and objs[0] is obj:
        obj.delete()
        return True
    return False
0
source

Source: https://habr.com/ru/post/1725833/


All Articles