Junior — Middle
Explain what a ForeignKey relationship in Django is and how it is used to establish relationships between models.
sobes.tech AI
Answer from AI
In Django, the ForeignKey relationship is used to establish a 'many-to-one' relationship between models. This means that one record in one model can be linked to multiple records in another model.
For example, if you have Author and Book models, each book can have one author, but an author can have many books. In the Book model, you add a field author = models.ForeignKey(Author, on_delete=models.CASCADE) to link the book to the author.
Example:
from django.db import models
class Author(models.Model):
name = models.CharField(max_length=100)
class Book(models.Model):
title = models.CharField(max_length=200)
author = models.ForeignKey(Author, on_delete=models.CASCADE)
Here, on_delete=models.CASCADE means that when an author is deleted, all related books will also be deleted.
Thus, ForeignKey allows navigation from the 'many' object to the 'one' object and enables the use of related data in queries and templates.