Relationships

Three kinds, matching the three ways records relate.

ForeignKey is many-to-one: many posts, one author.

ManyToManyField is many-to-many: a post has many tags, a tag has many posts.

OneToOneField is one-to-one: a user has one profile.

on_delete is required, and it is a real decision. Django refuses to guess what should happen to a post when its author is deleted.

CASCADE deletes the posts too.

PROTECT refuses to delete the author while posts exist.

SET_NULL keeps the posts and empties the field, which needs null=True.

People pick CASCADE because it appears in every tutorial. For anything you would be upset to lose, PROTECT is often the honest answer.

related_name is what you call the reverse direction. With related_name="posts" on the author field, you write user.posts.all(). Without it, Django names it post_set, which works and reads badly everywhere it appears.

null and blank are different things. null=True means the database column may be empty. blank=True means a form may leave it empty. Text fields usually want blank=True alone: an empty string is a perfectly good empty value and having two of them, empty string and NULL, causes confusion later.

Mark this lesson complete

Signed in, your progress follows you to every device.

Next: Practice Test →
← Back