In Django, a foreign key is a field that establishes a relationship between two models, creating a link between them. This link is used to represent one-to-many or many-to-one relationships between the models. Here's how you can define and use a foreign key in a Django model:
Let's say you have two models: Author
and Book
, where each book is written by a single author, and each author can have multiple books.
from django.db import models # Author model class Author(models.Model): name = models.CharField(max_length=100) birth_date = models.DateField() def __str__(self): return self.name # Book model with a foreign key to Author class Book(models.Model): title = models.CharField(max_length=200) publication_date = models.DateField() author = models.ForeignKey(Author, on_delete=models.CASCADE) def __str__(self): return self.title
In this example:
We define an Author
model with fields for the author's name and birth date.
We define a Book
model with fields for the book's title, publication date, and a foreign key named author
that links each book to an author. The on_delete=models.CASCADE
argument specifies that if an author is deleted, all associated books should also be deleted (cascade delete).
Now, you can create instances of these models, and they will be related through the foreign key. Here's how you can use them:
# Creating an author author1 = Author.objects.create(name="J.K. Rowling", birth_date="1965-07-31") # Creating books associated with the author book1 = Book.objects.create(title="Harry Potter and the Philosopher's Stone", publication_date="1997-06-26", author=author1) book2 = Book.objects.create(title="Harry Potter and the Chamber of Secrets", publication_date="1998-07-02", author=author1) # Querying the author's books author_books = Book.objects.filter(author=author1) for book in author_books: print(book.title)
In this code:
We create an Author
instance (author1
) and two Book
instances (book1
and book2
) associated with that author.
We can query the books written by a specific author using the filter()
method.
The foreign key relationship allows you to navigate between the two models, making it easy to work with related data in your Django application.
How to define a Foreign Key in Django Model
from django.db import models class Author(models.Model): name = models.CharField(max_length=100) class Book(models.Model): title = models.CharField(max_length=100) author = models.ForeignKey(Author, on_delete=models.CASCADE)
Django Foreign Key with related_name
related_name
for a Foreign Key relationship in Django.from django.db import models class Author(models.Model): name = models.CharField(max_length=100) class Book(models.Model): title = models.CharField(max_length=100) author = models.ForeignKey(Author, on_delete=models.CASCADE, related_name='books')
Django Foreign Key on_delete options
on_delete
parameter when defining a Foreign Key relationship in Django models.from django.db import models class Author(models.Model): name = models.CharField(max_length=100) class Book(models.Model): title = models.CharField(max_length=100) author = models.ForeignKey(Author, on_delete=models.SET_NULL, null=True)
How to access related objects in Django Foreign Key
book = Book.objects.get(pk=1) related_author = book.author
Django Foreign Key through and through_fields
through
and through_fields
parameters with Foreign Key relationships in Django.from django.db import models class Author(models.Model): name = models.CharField(max_length=100) class Book(models.Model): title = models.CharField(max_length=100) author = models.ForeignKey(Author, on_delete=models.CASCADE) class Editor(models.Model): name = models.CharField(max_length=100) book = models.ForeignKey(Book, on_delete=models.CASCADE)
Django Foreign Key backward relationship
author = Author.objects.get(pk=1) books = author.book_set.all()
Django Foreign Key limit_choices_to
limit_choices_to
parameter.from django.db import models class Author(models.Model): name = models.CharField(max_length=100) is_active = models.BooleanField(default=True) class Book(models.Model): title = models.CharField(max_length=100) author = models.ForeignKey(Author, on_delete=models.CASCADE, limit_choices_to={'is_active': True})
Django Foreign Key with unique constraint
from django.db import models class Author(models.Model): name = models.CharField(max_length=100, unique=True) class Book(models.Model): title = models.CharField(max_length=100) author = models.ForeignKey(Author, on_delete=models.CASCADE)
Django Multiple Foreign Keys in one model
from django.db import models class Author(models.Model): name = models.CharField(max_length=100) class Editor(models.Model): name = models.CharField(max_length=100) class Book(models.Model): title = models.CharField(max_length=100) author = models.ForeignKey(Author, on_delete=models.CASCADE) editor = models.ForeignKey(Editor, on_delete=models.CASCADE)
Django Foreign Key to self (Recursive Foreign Key)
from django.db import models class Category(models.Model): name = models.CharField(max_length=100) parent_category = models.ForeignKey('self', on_delete=models.CASCADE, null=True, blank=True)
docker-toolbox worksheet-function dataset attributes percentage dockerfile grayscale gateway inertiajs kafka-consumer-api