0
0
Djangoframework~5 mins

ManyToManyField for many-to-many in Django

Choose your learning style9 modes available
Introduction

A ManyToManyField lets you connect many items from one list to many items from another list. It helps show relationships where things belong to each other in groups.

You want to link students to many classes, and classes have many students.
You want to connect books to many authors, and authors write many books.
You want to tag blog posts with many tags, and tags can be on many posts.
You want to assign many skills to employees, and skills can belong to many employees.
Syntax
Django
class ModelName(models.Model):
    field_name = models.ManyToManyField(OtherModel, related_name='reverse_name')
The ManyToManyField creates a special table behind the scenes to link the two models.
Use related_name to access the reverse relationship easily.
Examples
This example links students and courses so each course can have many students and each student can join many courses.
Django
class Student(models.Model):
    name = models.CharField(max_length=100)

class Course(models.Model):
    title = models.CharField(max_length=100)
    students = models.ManyToManyField(Student, related_name='courses')
Books can have many authors and authors can write many books.
Django
class Author(models.Model):
    name = models.CharField(max_length=100)

class Book(models.Model):
    title = models.CharField(max_length=100)
    authors = models.ManyToManyField(Author, related_name='books')
Sample Program

This code defines posts and tags. Each post can have many tags, and each tag can belong to many posts. You can add tags to posts and find posts by tags.

Django
from django.db import models

class Tag(models.Model):
    name = models.CharField(max_length=30)

class Post(models.Model):
    title = models.CharField(max_length=100)
    tags = models.ManyToManyField(Tag, related_name='posts')

# Usage example (in Django shell):
# tag1 = Tag.objects.create(name='django')
# tag2 = Tag.objects.create(name='python')
# post = Post.objects.create(title='Learning Django')
# post.tags.add(tag1, tag2)
# print(post.tags.all())  # Shows all tags for the post
# print(tag1.posts.all())  # Shows all posts with tag1
OutputSuccess
Important Notes

ManyToManyField automatically creates a join table to manage the connections.

You can add or remove related items using methods like add(), remove(), and clear() on the related manager.

Remember to run migrations after adding ManyToManyField to create the necessary database tables.

Summary

ManyToManyField connects many items from one model to many items from another.

It creates a hidden table to store these connections.

You can easily add, remove, or query related items using this field.