Code-Memo

Relationships in Models

Relationships between models allow you to define how different data models are interconnected in the database. They enable efficient data querying, retrieval, and manipulation.

ForeignKey Relationship

The ForeignKey relationship establishes a many-to-one association between two models, where each instance of the child model (with the foreign key) relates to exactly one instance of the parent model.

Suppose you have Author and Book models where each book is authored by one author:

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)

OneToOneField Relationship

The OneToOneField relationship is a specific type of ForeignKey where each instance of the child model is associated with exactly one instance of the parent model.

Suppose you have a Profile model linked to a User model:

from django.contrib.auth.models import User

class Profile(models.Model):
    user = models.OneToOneField(User, on_delete=models.CASCADE)
    bio = models.TextField()

ManyToManyField Relationship

The ManyToManyField relationship allows for a many-to-many association between two models, where each instance of one model can be related to multiple instances of another model.

Suppose you have Student and Course models where students can enroll in multiple courses:

class Student(models.Model):
    name = models.CharField(max_length=100)
    courses = models.ManyToManyField('Course')

class Course(models.Model):
    name = models.CharField(max_length=100)

Use Cases for Relationships