0 day streak
python / intermediate
Snippet

Django Model Relationships with ForeignKey and ManyToMany

Django's ORM handles relational data through model fields. ForeignKey creates a many-to-one relationship (one Author has many Books), while ManyToManyField allows bidirectional many-to-many relationships (Authors can collaborate on multiple Books, and Books can have multiple collaborators). The on_delete=models.CASCADE ensures referential integrity by deleting related books when an author is deleted.

snippet.py
python
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
from django.db import models
class Author(models.Model):
name = models.CharField(max_length=100)
email = models.EmailField()
def __str__(self):
return self.name
class Book(models.Model):
title = models.CharField(max_length=200)
author = models.ForeignKey(Author, on_delete=models.CASCADE, related_name='books')
collaborators = models.ManyToManyField(Author, related_name='collaborated_books', blank=True)
published_date = models.DateField()
rating = models.DecimalField(max_digits=3, decimal_places=2, default=0.0)
def __str__(self):
return self.title
django
Breakdown
1
class Author(models.Model):
Defines the Author model inheriting from Django's Model base class
2
author = models.ForeignKey(Author, on_delete=models.CASCADE)
Creates a many-to-one relationship; each Book belongs to one Author
3
collaborators = models.ManyToManyField(Author)
Enables many-to-many relationship between Book and Author for collaboration
4
on_delete=models.CASCADE
When the referenced Author is deleted, all related Books are automatically deleted