How do I access the properties of a many-to-many "through" table from a django template? How do I access the properties of a many-to-many "through" table from a django template? python python

How do I access the properties of a many-to-many "through" table from a django template?


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 %}


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().


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 %}