ForeignKey (Django)

A ForeignKey creates a many-to-one relationship between two Django models, like many posts belonging to one author. It stores the related object's id and lets you access the related object as an attribute.

Django

ForeignKey is the most common relationship field. Putting author = ForeignKey(Author, on_delete=...) on Post means each post links to one author, while one author can have many posts. You access the link as post.author, and the reverse direction as author.post_set (or a custom related_name).

The on_delete argument is required and decides what happens to a post when its author is deleted: CASCADE deletes the posts too, PROTECT blocks deletion, SET_NULL clears the link (needs null=True), and SET_DEFAULT/SET() set a fallback.

Set related_name to make the reverse accessor readable: ForeignKey(Author, related_name='posts') turns author.post_set into author.posts. Spanning a ForeignKey in queries uses double underscores: Post.objects.filter(author__name='Ana').

Syntax

author = models.ForeignKey(Author, on_delete=models.CASCADE)

Examples

Python

class Post(models.Model):
    author = models.ForeignKey(
        "Author",
        on_delete=models.CASCADE,
        related_name="posts",
    )

# post.author -> one Author
# author.posts.all() -> that author's posts

Learn it in a lesson

See also

Back to the Dictionary