Django 使用多对多字段
示例
我们从第一个示例使用此模型:
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 = 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