使用 ManyToMany 欄位

我們從第一個例子中使用這個模型:

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)

將 Tom 和 Bill 新增到夜總會:

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)

誰在俱樂部?

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

會給你

Tom
Bill