Junior — Middle
Explain the principle of how ManyToManyField works in Django and its purpose.
sobes.tech AI
Answer from AI
ManyToManyField in Django is used to create a many-to-many relationship between two models. This means that one object of the first model can be related to multiple objects of the second model and vice versa.
How it works:
- Django creates an intermediate table (a relationship table) that stores pairs of identifiers of related objects.
- When a relationship is added in
ManyToManyField, a corresponding record is added to this table. - When querying, Django automatically performs a JOIN between the tables to retrieve related objects.
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, one book can have multiple authors, and one author can write multiple books. ManyToManyField simplifies working with such relationships by hiding the details of the intermediate table.