使用 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