Overview
Django simplifies the establishment of relationships between models, enabling the creation of a well-connected and organized database. This documentation provides insights into defining and leveraging model relationships.
Type 1 : One-to-One Relationship
Every record in one model is linked to exactly one record in another model in a one-to-one relationship.
Example :
class Pet(models.Model) : name = models.CharField(max_length=50) species = models.CharField(max_length=50)class PetMedicalRecord(models.Model) : pet = models.OneToOneField(Pet, on_delete=models.CASCADE) vaccination_status = models.BooleanField(default=False) last_checkup_date = models.DateField()
In this scenario, each pet has a unique medical record captured in the PetMedicalRecord model, forming a one-to-one relationship.
Type 2 : One-to-Many Relationship
Each record in one model can be related to several records in another, whereas each record in the second model is connected to a single record in the first, according to a one-to-many relationship.
Example :
class Manufacturer(models.Model): name = models.CharField(max_length=100) location = models.CharField(max_length=150)class Product(models.Model): manufacturer = models.ForeignKey(Manufacturer, on_delete=models.CASCADE) product_name = models.CharField(max_length=200) price = models.DecimalField(max_digits=8, decimal_places=2)
In this example, a manufacturer can produce multiple products, but each product is associated with only one manufacturer.
Type 3 : Many-to-Many Relationship
A many-to-many relationship implies that each record in one model can be linked with multiple records in another model.
Example :
class Teacher(models.Model): name = models.CharField(max_length=100)class Classroom(models.Model): teachers = models.ManyToManyField(Teacher) room_number = models.CharField(max_length=10)
In this scenario, a teacher can be assigned to multiple classrooms, and a classroom can have multiple teachers.
Navigating Relationships
Once relationships are established, you can traverse them using querysets. For instance, to retrieve all books by a specific author :
author = Author.objects.get(name='J.K. Rowling') books_by_author = author.book_set.all()
Conclusion
Building a robust and networked database in Django requires an understanding of and efficient use of model relationships. Select a relationship type that improves the overall cohesiveness of your application and fits in with your data structure.