Django - 在ManyToManyRelation中的级联删除 [英] Django - Cascade deletion in ManyToManyRelation

查看:735
本文介绍了Django - 在ManyToManyRelation中的级联删除的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用以下相关模型(一个博​​客条目可以有多个修订版本):

Using the following related models (one blog entry can have multiple revisions):

class BlogEntryRevision(models.Model):
    revisionNumber = models.IntegerField()
    title = models.CharField(max_length = 120)
    text = models.TextField()
    [...]

class BlogEntry(models.Model):
    revisions = models.ManyToManyField(BlogEntryRevision)
    [...]

当相应的 BlogEntry BlogEntryRevision c>被删除?默认情况下,如果其他方面的对象被删除,则将对象保持在多对多关系中。任何方式这样做 - 最好不要覆盖 BlogEntry.delete

How can I tell Django to delete all related BlogEntryRevisions when the corresponding BlogEntry is deleted? The default seems to be to keep objects in a many-to-many relation if an object of the "other" side is deleted. Any way to do this - preferably without overriding BlogEntry.delete?

推荐答案

我认为你误解了ManyToMany关系的本质。你说的相应的BlogEntry被删除。但是,ManyToMany的整体观点是每个BlogEntryRevision都有与其相关的多个 BlogEntries。 (当然,每个BlogEntry都有多个BlogEntryRevisions,但是你已经知道了。)

I think you are misunderstanding the nature of a ManyToMany relationship. You talk about "the corresponding BlogEntry" being deleted. But the whole point of a ManyToMany is that each BlogEntryRevision has multiple BlogEntries related to it. (And, of course, each BlogEntry has multiple BlogEntryRevisions, but you know that already.)

从你使用的名字,以及你想要删除级联的事实功能,我认为你会更好的从一个标准的外键从BlogEntryRevision到BlogEntry。只要您没有在该ForeignKey上设置 null = True ,则删除将被级联 - 当BlogEntry被删除时,所有修订版也将被执行。

From the names you have used, and the fact that you want this deletion cascade functionality, I think you would be better off with a standard ForeignKey from BlogEntryRevision to BlogEntry. As long as you don't set null=True on that ForeignKey, deletions will cascase - when the BlogEntry is deleted, all Revisions will be too.

这篇关于Django - 在ManyToManyRelation中的级联删除的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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