Constraints keep the integrity of your system and prevent you from shooting yourself in the foot. Foreign keys are a special type of constraint because, unlike unique, check, and primary keys, they span more than one relation. This makes foreign keys harder to enforce and harder to get right.
In this article, I demonstrate common pitfalls, potential optimizations, and implicit behavior related to foreign keys.
Table of Contents
Watch 📺 This article is inspired by a talk I gave at DjangoCon EU. Watch it here.
Imagine a simple application to manage a product catalog:
Generated using dbdiagram.io
The first table, or model, in the catalog is the Category model:
class Category ( models . Model ): id : int = models . BigAutoField ( primary_key = True ) name : str = models . CharField ( max_length = 50 )
Categories can be "household items", "fruit", "apparel", and so on.
Next, a model to store products:
... continue reading