49

From the Django documentation...

When you're only dealing with simple many-to-many relationships such as mixing and matching pizzas and toppings, a standard ManyToManyField is all you need. However, sometimes you may need to associate data with the relationship between two models.

For example, consider the case of an application tracking the musical groups which musicians belong to. There is a many-to-many relationship between a person and the groups of which they are a member, so you could use a ManyToManyField to represent this relationship. However, there is a lot of detail about the membership that you might want to collect, such as the date at which the person joined the group.

For these situations, Django allows you to specify the model that will be used to govern the many-to-many relationship. You can then put extra fields on the intermediate model. The intermediate model is associated with the ManyToManyField using the through argument to point to the model that will act as an intermediary. For our musician example, the code would look something like this:

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

    def __unicode__(self):
        return self.name

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

    def __unicode__(self):
        return self.name

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

Now that you have set up your ManyToManyField to use your intermediary model (Membership, in this case), you're ready to start creating some many-to-many relationships. You do this by creating instances of the intermediate model:

ringo = Person.objects.create(name="Ringo Starr")
paul = Person.objects.create(name="Paul McCartney")
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()
[<Person: Ringo Starr>]

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

m2 = Membership.objects.create(person=paul, group=beatles,
...     date_joined=date(1960, 8, 1),
...     invite_reason= "Wanted to form a band.")

beatles.members.all()
[<Person: Ringo Starr>, <Person: Paul McCartney>]

source: http://docs.djangoproject.com/en/dev/topics/db/models/#intermediary-manytomany

My question is, how do I set up my view and template to access these additional attributes. Say I have a band page and I want to display the band name, iterate through the membership records and display names and date_joined.

Should I pass a band object to the template? Or do I pass the membership objects somehow?

And how would I create the for loops in in the template?

Thanks.

Community
  • 1
  • 1
Alex
  • 2,350
  • 2
  • 20
  • 17
  • 1
    I would consider shortening excerpts from django docs a little. People that are likely to respond are probably already familiar with them and it would be easier to spot actual question that way. – cji Jul 30 '10 at 04:57

3 Answers3

41

The easiest way is just to pass the band to the template. Templates are capable of navigating the relationships between models and there is both members and membership_set queryset managers on Group. So here is how I would do it:

view:

def group_details(request, group_id):
    group = get_object_or_404(Group, pk=group_id)
    return render_to_response('group_details.html',
                              {'group': group})

template:

<h2>{{ group.name }}</h2>
{% for membership in group.membership_set.all %}
    <h3>{{ membership.person }}</h3>
    {{ membership.date_joined }}
{% endfor %}
Rory Hart
  • 1,813
  • 1
  • 19
  • 19
  • 2
    That works perfectly. I was trying iterate through group.membership.all. I need to read up on _set. Thanks! – Alex Jul 30 '10 at 14:18
  • But if you need something more complex i.e. ordering, filtering etc standard practice is to do it in the view and then pass it in via the context? – CpILL Sep 29 '15 at 14:22
  • One important point is that the class name in lower case of the through table is used "membership",. – MagicLAMP Mar 10 '16 at 12:16
7

I'm not sure whether it's only solution or not, but passing relation objects to the template certainly works. In your view, get QuerySet of Membership objects:

rel = Membership.objects.filter( group = your_group ).select_related()

and pass it to template, where you can iterate over it with {% for %}

{% for r in rel %}
     {{ r.person.name }} joined group {{ r.group.name }} on {{ r.date_joined }}<br />
{% endfor %}

Note that this should not perform any additional queries because of select_related().

cji
  • 6,635
  • 2
  • 20
  • 16
0

Rory Hart's answer is mostly correct. It allows you to use intermediate (through) table in the ManyToMany relationship.

However, the loop in the template should be modified using select_related as cji suggests, in order to avoid hitting the database with additional queries:

<h2>{{ group.name }}</h2>
{% for membership in group.membership_set.select_related %}
    <h3>{{ membership.person.name }}</h3>
    {{ membership.date_joined }}
{% endfor %}
Quique
  • 909
  • 10
  • 8