Django FK on_delete defaults to CASCADE

Andy Byers
Mar 12, 2017 · 1 min read

What does this mean!? Well, lets make an example.

class Company(models.Model):
name = models.CharField(max_length=100)
logo = models.ForeignKey(File, null=True, blank=True)
class File(models.Model):
filename = models.CharField(max_length=100)
mime = models.CharField(max_length=100)

Say we have an Company object and a File object. The file object is set to be the logo.

company = models.Company.objects.create(name='A Company')
file = models.File.objects.create(filename='file.jpg', mime='jpeg')
company.logo = file
company.save()

If we then delete the file

file.delete()

Then we will actually also delete the company object because by default django will, on delete, cascade. So, we have to set the on_delete attribute to avoid this.

class Company(models.Model)
name = models.CharField(max_length=100)
logo = models.ForeignKey(File, null=True, blank=True, on_delete=models.SET_NULL)

If the File object is deleted nowm the logo will be set to NULL rather than deleting the object.

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store