问题描述
使用以下相关模型(一篇博文可以多次修改):
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
被删除时,如何告诉 Django 删除所有相关的 BlogEntryRevision
?如果删除另一方"的对象,则默认似乎是将对象保持在多对多关系中.有什么方法可以做到这一点 - 最好不要覆盖 BlogEntry.delete
?
How can I tell Django to delete all related BlogEntryRevision
s 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
?
推荐答案
我认为您误解了多对多关系的本质.你说相应的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 被删除时,所有的 Revisions 也会被删除.
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 cascade - when the BlogEntry is deleted, all Revisions will be too.
从 Django 2.0 开始
ForeignKey
初始值设定项现在要求您指定 on_delete
参数:
The ForeignKey
initializer now requires you to specify the on_delete
parameter:
from django.db import models
from .models import MyRelatedModel
class model(models.Model):
related_model = models.ForeignKey(MyRelatedModel, on_delete=models.CASCADE)
这篇关于Django - ManyToManyRelation 中的级联删除的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!