In a many-to-many
relationship, records in one model can be associated with multiple records in another model, and vice versa.
For example, lets create a model to show the demo of many-to-many
relationship.
class Hobby(models.Model):
name = models.CharField(max_length=50)
persons = models.ManyToManyField(Person)
After adding this model, you need to run the python manage.py makemigrations
and python manage.py migrate
command.
python manage.py makemigrations
python manage.py migrate
You can create and assign values for the Hobbies
Model as follows :
from modeldemo.models import *
hobby1 = Hobby.objects.create(name='Reading')
hobby2 = Hobby.objects.create(name='Programming')
person = Person.objects.get(id=1)
hobby1.persons.add(person)
hobby2.persons.add(person)
Hobby.objects.get(name='Reading').persons.all()
Hobby.objects.get(name='Reading').persons.all()
, can be used to get all the Persons
who have the hobby as Reading
.
In this example, we have a many-to-many
relationship between Person
and Hobby
, where multiple persons can share the same hobby, and a person can have multiple hobbies.