About Lesson
1. One-to-One Relationships
Use OneToOneField
for relationships where each record in one table corresponds to exactly one record in another.
Example:
class Author(models.Model):
name = models.CharField(max_length=50)
class Profile(models.Model):
author = models.OneToOneField(Author, on_delete=models.CASCADE)
bio = models.TextField()
2. Many-to-One Relationships
Use ForeignKey
for relationships where multiple records in one table relate to a single record in another.
Example:
class Author(models.Model):
name = models.CharField(max_length=50)
class Book(models.Model):
title = models.CharField(max_length=100)
author = models.ForeignKey(Author, on_delete=models.CASCADE)
3. Many-to-Many Relationships
Use ManyToManyField
for relationships where records in one table relate to multiple records in another.
Example:
class Book(models.Model):
title = models.CharField(max_length=100)
class Genre(models.Model):
name = models.CharField(max_length=50)
books = models.ManyToManyField(Book)
Join the conversation