Django模型ON DELETE CASCADE策略,模拟ON DELETE RESTRICT代替,一般解决方案 [英] Django model ON DELETE CASCADE policy, emulate ON DELETE RESTRICT instead, general solution

查看:290
本文介绍了Django模型ON DELETE CASCADE策略,模拟ON DELETE RESTRICT代替,一般解决方案的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想删除一个模型的实例,但是只有当外部键指向的另外一个类没有任何其他实例时。从Django文档:

I'd like to delete an instance of a model, but only if it doesn't have any other instance of another class with a foreign key pointing to it. From Django documentation:


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

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

在给定的示例中:

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(),但是我正在为任何给定的模型寻找一个更通用的解决方案。

Should print the error. I know I can check for specific instances the foreignkey sets, like in this case check t.TestB_set(), but I am looking for a more general solution for any given model.

推荐答案

我终于用这个 Nullable ForeignKeys并删除引用的模型实例,解决方案如下所示:

I finally solved it using this Nullable ForeignKeys and deleting a referenced model instance, the solution looks like:

    # 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

这篇关于Django模型ON DELETE CASCADE策略,模拟ON DELETE RESTRICT代替,一般解决方案的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆