Django模型ON DELETE CASCADE策略,改为模拟ON DELETE RESTRICT,一般解决方案

时间:2009-12-16 10:54:20

标签: python django django-models

我想删除一个模型的实例,但前提是它没有任何其他类的实例,并且外键指向它。来自Django文档:

  

当Django删除一个对象时,它会模拟SQL约束ON DELETE CASCADE的行为 - 换句话说,任何具有指向要删除的对象的外键的对象都将随之删除。

在给定的例子中:

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
# ........

我想要像:

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"

应该打印错误。我知道我可以检查外键设置的具体实例,比如在这种情况下检查t.TestB_set(),但我正在为任何给定的模型寻找更通用的解决方案。

3 个答案:

答案 0 :(得分:2)

我终于使用这个Nullable ForeignKeys and deleting a referenced model instance解决了它,解决方案如下:

    # 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

答案 1 :(得分:0)

检查相关对象长度

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

答案 2 :(得分:0)

在Django 1.3中删除了CollectedObjects() - 这是当前的方法:

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