Foreign Key Django Model

Foreign Key Django Model

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:

  1. We define an Author model with fields for the author's name and birth date.

  2. 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.

Examples

  1. How to define a Foreign Key in Django Model

    • Description: This query aims to understand the syntax and usage of Foreign Keys in Django models.
    • Code:
      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)
      
  2. Django Foreign Key with related_name

    • Description: Users often seek information on how to specify a custom related_name for a Foreign Key relationship in Django.
    • Code:
      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')
      
  3. Django Foreign Key on_delete options

    • Description: This query explores the different options available for the on_delete parameter when defining a Foreign Key relationship in Django models.
    • Code:
      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)
      
  4. How to access related objects in Django Foreign Key

    • Description: Users often inquire about accessing related objects through a Foreign Key relationship in Django models.
    • Code:
      book = Book.objects.get(pk=1)
      related_author = book.author
      
  5. Django Foreign Key through and through_fields

    • Description: Users may want to understand how to use through and through_fields parameters with Foreign Key relationships in Django.
    • Code:
      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)
      
      
  6. Django Foreign Key backward relationship

    • Description: This query explores how to access the reverse relationship (backward relationship) of a Foreign Key in Django models.
    • Code:
      author = Author.objects.get(pk=1)
      books = author.book_set.all()
      
  7. Django Foreign Key limit_choices_to

    • Description: Users may want to limit the choices available in a Foreign Key field based on certain conditions. This query explores the limit_choices_to parameter.
    • Code:
      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})
      
  8. Django Foreign Key with unique constraint

    • Description: Users may want to enforce a unique constraint on a Foreign Key field in Django models.
    • Code:
      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)
      
  9. Django Multiple Foreign Keys in one model

    • Description: This query explores how to define multiple Foreign Keys within a single Django model.
    • Code:
      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)
      
  10. Django Foreign Key to self (Recursive Foreign Key)

    • Description: Users may inquire about how to establish a Foreign Key relationship to the same model, also known as a Recursive Foreign Key.
    • Code:
      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)
      

More Tags

docker-toolbox worksheet-function dataset attributes percentage dockerfile grayscale gateway inertiajs kafka-consumer-api

More Python Questions

More Statistics Calculators

More Retirement Calculators

More Fitness Calculators

More Genetics Calculators