Junior — Middle
How is the many-to-many relationship managed in Django ORM?
sobes.tech AI
Answer from AI
In Django ORM, a many-to-many relationship is implemented through a special intermediate table that stores pairs of keys from related models.
By default, Django automatically creates this table unless a custom model for the relationship is explicitly specified.
Example:
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)
authors = models.ManyToManyField(Author)
Here, authors is a many-to-many field that creates a table with two columns: book_id and author_id.
You can also define your own intermediate model if you need to add additional fields:
class Authorship(models.Model):
author = models.ForeignKey(Author, on_delete=models.CASCADE)
book = models.ForeignKey(Book, on_delete=models.CASCADE)
role = models.CharField(max_length=50) # for example, "editor"
class Book(models.Model):
title = models.CharField(max_length=100)
authors = models.ManyToManyField(Author, through='Authorship')
Thus, Django ORM manages the many-to-many relationship through an intermediate table and provides a convenient API for adding, removing, and querying related objects.