Django Many-to-many relationships Using ManyToMany Fields


Example

We use this model from the first example:

class Person(models.Model):
    name = models.CharField(max_length=50)
    description = models.TextField()

class Club(models.Model):
    name = models.CharField(max_length=50)
    members = models.ManyToManyField(Person)

Add Tom and Bill to the Nightclub:

tom = Person.objects.create(name="Tom", description="A nice guy")
bill = Person.objects.create(name="Bill", description="Good dancer")

nightclub = Club.objects.create(name="The Saturday Night Club")
nightclub.members.add(tom, bill)

Who is in the club?

for person in nightclub.members.all():
    print(person.name)

Will give you

Tom
Bill