Intermediate tables in Django
Monday, April 20th, 2009Intermediate, intermediary, join tables in Django are something I’ve just ranted about on Twitter. Twitter’s great, because rants are limited to 140chars, so you don’t look so silly when you find the answer in the documentation.
Django’s documentation says that you can add ManyToMany join tables using the “through” parameter.
http://docs.djangoproject.com/en/dev/topics/db/models/#extra-fields-on-many-to-many-relationships
That table can hold useful extra fields. The documentation shows how to query against those fields, but not how to return them to view.
Ideally, we want to return them in a template. My example is a school with members, and a year for each.
Models:
class School(models.Model): name = models.CharField(max_length=200) members = models.ManyToManyField(Member, through='SchoolMember') class Member(models.Model): name = models.CharField(max_length=200) class SchoolMember(models.Model): member = models.ForeignKey(Member) school = models.ForeignKey(School) year = models.IntegerField(default=1900)
Template:
{% for myschool in myschoollist %}
{{ myschool.name }}
{% for myschoolmember in myschool.schoolmember_set|dictsort:"year"?%}
{{ myschoolmember.year }}
{{ myschoolmember.member.name }}
{% endfor %}
{% endfor %}
I think this works, but I’m not sure it’s optimal. Can anyone set me straight?
Updated: ?I’ve added sorting to show each year in order.