liveBook · Manning

On_delete

As explained in Django in Action

on_delete is a Django ForeignKey parameter specifying the behavior applied to a relationship when the referenced object is deleted.

on_delete is the ForeignKey rule for what happens to related objects when the referenced object is deleted. It makes the deletion policy explicit instead of leaving dangling relationships to surprise you later. section 4.7.1

Common policies include:

  • CASCADE deletes associated objects too. A Room with venue = models.ForeignKey(Venue, on_delete=models.CASCADE) disappears when its Venue is deleted. section 4.7.1
  • SET_NULL changes the relationship field to NULL instead, but the field must permit database NULL values with null=True. section 4.7.1
  • Other choices can invoke different behavior, including a function, so select the policy that matches the relationship’s meaning. section 4.7.1

A venue with rooms

Venue.objects.create(name="CBGB") can own Room objects such as Red and Blue. With CASCADE, deleting CBGB also deletes those rooms; the reverse relationship is available through cbgb.room_set.all().

How Django in Action covers it

How deep it goes
Defines CASCADE and SET_NULL, explains null=True, and mentions additional choices without listing their complete API.
Examples
Uses Venue and Room models plus shell-created CBGB, Red, and Blue objects to demonstrate forward and reverse relationships.
What it assumes
Assumes basic Django models while teaching the required ForeignKey arguments and database-versus-form emptiness distinction.
What you can do after
Configure Django ForeignKey deletion behavior and permit nullable relationships when using SET_NULL.
How it connects
Connects ForeignKey fields with one-to-many relationships, database NULL values, and Django Admin emptiness controls.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Django in Action. The section links point to the parts of the book it draws on.