Django FK on_delete defaults to CASCADE

Andy Byers
1 min readMar 12, 2017

--

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.

Sign up to discover human stories that deepen your understanding of the world.

Free

Distraction-free reading. No ads.

Organize your knowledge with lists and highlights.

Tell your story. Find your audience.

Membership

Read member-only stories

Support writers you read most

Earn money for your writing

Listen to audio narrations

Read offline with the Medium app

--

--

Andy Byers
Andy Byers

Written by Andy Byers

Pub Tech developer for Birkbeck CTP

Responses (3)

Write a response