0 day streak
python / beginner
Snippet

Defining ForeignKey Relationships

ForeignKeys establish a many-to-one relationship. The on_delete parameter determines what happens to the post if its category is deleted.

snippet.py
python
1
2
3
4
from django.db import models
class BlogPost(models.Model):
category = models.ForeignKey('Category', on_delete=models.CASCADE)
django
Breakdown
1
models.ForeignKey('Category', ...)
Links the current model to another model named 'Category'.
2
on_delete=models.CASCADE
Ensures that if a Category is deleted, all related BlogPosts are also automatically deleted.