Search code examples
pythondjangodjango-modelsmany-to-manymodels

adding to a many to many relation django


Lets look at the django documentation code for adding members of the bettles.

First we have our models:

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)

now we have the code to add to the many to many relation:

# 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>]>

as well do we need to just set the many to many relation like is done in the Group model?

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

then go to the table that is holding all the foreign keys for the many to many relation and just add our saved objects?

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

and then done?

We don't have to do any thing else with the

members field of the Group model?

i.e this one?

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

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

If so yay! But what is this thing all about?

ringo.group_set.all()

Solution

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

    to understand it you can read the doc related-objects-reference at the part of

    Both sides of a ManyToManyField relation: