增加了许多关系django

时间:2017-10-23 20:59:15

标签: python django django-models many-to-many models

让我们看一下用于添加bettles成员的django文档代码。

首先我们有我们的模型:

from django.db import models

class Person(models.Model):
    name = models.CharField(max_length=128)

    def __str__(self):              # __unicode__ on Python 2
        return self.name

class Group(models.Model):
    name = models.CharField(max_length=128)
    members = models.ManyToManyField(Person, through='Membership')

    def __str__(self):              # __unicode__ on Python 2
        return self.name

class Membership(models.Model):
    person = models.ForeignKey(Person, on_delete=models.CASCADE)
    group = models.ForeignKey(Group, on_delete=models.CASCADE)
    date_joined = models.DateField()
    invite_reason = models.CharField(max_length=64)

现在我们有了添加到多对多关系的代码:

# create a person named ringo
ringo = Person.objects.create(name="Ringo Starr")

# create a group named the beatles (terrible band so boring)

beatles = Group.objects.create(name="The Beatles")
>>> m1 = Membership(person=ringo, group=beatles,
...     date_joined=date(1962, 8, 16),
...     invite_reason="Needed a new drummer.")
>>> m1.save()
>>> beatles.members.all()
<QuerySet [<Person: Ringo Starr>]>

# what is this doing tho? 

 ringo.group_set.all()
<QuerySet [<Group: The Beatles>]>

我们是否需要像Group模型中那样设置多对多的关系?

class Group(models.Model):
    name = models.CharField(max_length=128)
    members = models.ManyToManyField(Person, through='Membership')

    def __str__(self):              # __unicode__ on Python 2
        return self.name

然后转到包含多对多关系的所有外键的表,只需添加我们保存的对象?

m1 = Membership(person=ringo, group=beatles,
     date_joined=date(1962, 8, 16),
    invite_reason="Needed a new drummer.")
m1.save()

然后完成了?

我们不需要用

做任何其他事情

field模型的成员Group

即这一个?

class Group(models.Model):
    name = models.CharField(max_length=128)
    members = models.ManyToManyField(Person, through='Membership')

    # hes talking about me^^^^^^^^^^^^^^^^^^^^^^^^^^

如果是这样的话!但这件事到底是什么?

ringo.group_set.all()

1 个答案:

答案 0 :(得分:0)

# what is this doing tho? 
ringo.group_set.all()

要了解它,您可以阅读

部分的文档related-objects-reference
  

ManyToManyField关系的两端: