How do I stop this cascading delete from happening in Django?

落爺英雄遲暮 提交于 2020-08-27 06:59:15

问题


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")

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.


回答1:


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

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.

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




回答2:


As Thomas has said, the default on_delete behaviour of a ForeignKey is models.CASCADE. Implying the 'child' model will be deleted when the 'parent' model is deleted.

A simple solution would be to include on_delete=models.SET_NULL to each of the ForeignKey to Image fields of the Folder model like so:

front_thumbnail_image  = models.ForeignKey('Image',on_delete=models.SET_NULL, null=True, ...)
middle_thumbnail_image = models.ForeignKey('Image',on_delete=models.SET_NULL, null=True, ...)
back_thumbnail_image   = models.ForeignKey('Image',on_delete=models.SET_NULL, null=True, ...)


来源:https://stackoverflow.com/questions/13747886/how-do-i-stop-this-cascading-delete-from-happening-in-django

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!