如何阻止这种级联删除在Django中发生? [英] How do I stop this cascading delete from happening in Django?

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

问题描述

我在Django应用程序中具有三个模型类:

I have three model classes in a Django app:

class Folder(models.Model):
  ...
  folder = models.ForeignKey('Folder',null=True,blank=True,related_name='folders')
  front_thumbnail_image = models.ForeignKey('Image',verbose_name='Front Thumbnail',null=True,blank=True,related_name='front_thumbnail_for_folders')
  middle_thumbnail_image = models.ForeignKey('Image',verbose_name='Middle Thumbnail',null=True,blank=True,related_name='middle_thumbnail_for_folders')
  back_thumbnail_image = models.ForeignKey('Image',verbose_name='Back Thumbnail',null=True,blank=True,related_name='back_thumbnail_for_folders')

class Image(models.Model):
  ...
  folder = models.ForeignKey(Folder,related_name='images',null=True)

class ImageRepresentation(models.Model):
  ...
  image = models.ForeignKey(Image, related_name="image_representations")

给定此模型,当我删除 I时法师在管理站点中,我希望与该 Image 关联的 ImageRepresentation 也被删除,并且文件夹包含该 Image 单独保存。

Given this model, when I delete an Image in the admin site, I would expect the ImageRepresentations associated with that Image to be deleted as well, and the Folder enclosing that Image to be left alone.

管理站点告诉我,随附的文件夹也将被删除。我该怎么做才能达到预期的行为?我研究了删除级联规则,但是没有尝试。

The admin site tells me that the enclosing Folder will be deleted as well. What can I do to get the desired behavior? I looked into delete cascade rules, but nothing I tried seemed to work.

已编辑,在上添加了三个外键文件夹(缩略图)...我完全忽略了这些(显然)。老实说,没有其他关系。

Edited to add three foreign keys on Folder (the thumbnail image ones)... I totally overlooked those (obviously). There are no other relationships, honest.

推荐答案

创建 ForeignKey ,删除父对象时删除的内容由 on_delete 参数

When you create the ForeignKey, what gets deleted when the parent object is deleted is controlled by the on_delete parameter.

默认情况下, on_delete 设置为 models.CASCADE ,这将在删除父对象时删除子对象。其他配置选项都无法创建您要在此处报告的行为。

By default, on_delete is set to models.CASCADE, which will delete children objects when the parent is deleted. None of the other configuration options can create the behavior you are reporting here.

您是否有外键来自文件夹图像 ImageRepresentation ? (您的情况下的文件夹缩略图)

Do you have a Foreignkey from Folder to Image or ImageRepresentation? (folder thumbnail in your case)

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

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