ManyToManyField (Django)
A ManyToManyField models a many-to-many relationship, where each row on both sides can relate to many on the other — for example posts and tags. Django creates a hidden join table to store the links.
Django
When both sides can have many of the other — a post has many tags, a tag applies to many posts — you use ManyToManyField. Unlike ForeignKey, it stores no column on either model; Django creates an intermediate join table behind the scenes.
You manipulate the relationship with methods: post.tags.add(tag), post.tags.remove(tag), post.tags.set([...]), post.tags.clear(), and query it with post.tags.all(). Both directions are accessible, and related_name customizes the reverse accessor.
When you need extra data on the link itself (such as when a tag was added or who added it), supply your own join model with through=, which turns the implicit table into an explicit, queryable model.
Syntax
tags = models.ManyToManyField(Tag, related_name="posts")Examples
Python
class Tag(models.Model):
name = models.CharField(max_length=50)
class Post(models.Model):
tags = models.ManyToManyField(Tag, related_name="posts")
# usage
post.tags.add(tag1, tag2)
for t in post.tags.all():
print(t.name)