Search code examples
pythondjangomany-to-many

How do I iterate through a list of related objects in a django template?


I'm new to Django and I'm trying to get related models printing in a view. I'm pretty sure the DB itself is set up properly, including keys and such, and there is data in the table to play with. What I'm not sure about is

  • Am I wiring the models to the correct table and column names?
  • Am I loading the phones for each voter?
  • How do I iterate over the relationship itself?

I can get the voter information itself, but nothing I try with the related Phone model works.

Tables:

voters:
  id int primary key
  first_name varchar

phones:
  id int primary_key
  phone_number varchar

voter_phones:
  voter_id FK
  phone_id FK

Models:

from django.db import models


class Phone(models.Model):
    phone_number = models.CharField(max_length=255)

    class Meta:
        db_table = 'phones'


class Voter(models.Model):
    first_name = models.CharField(max_length=255)
    phones = models.ManyToManyField('Phone', through='VoterPhone', related_name='voters', through_fields=('voter_id', 'phone_id'))

    class Meta:
        db_table = 'voters'


class VoterPhone(models.Model):
    voter = models.ForeignKey('Voter', related_name='voter_phones')
    phone = models.ForeignKey('Phone', related_name='voter_phones')

    class Meta:
        db_table = 'voter_phones'

The view:

def results(request):
    voters = Voter.objects.all()
    return render(request, 'site/results.html', {'voters': voters})

The template:

{% for voter in voters %}
  {{ voter.first_name }}
  {% for phone in voter.phones_set.all %}
    {{ phone.phone_number }}
  {% endfor %}
{% endfor %}

The end result is a list of voter names, and no phone numbers. What am I missing?

EDIT: I created a local database, generated and ran django migrations, and inserted some dummy data. I still get no phone numbers.


Solution

  • I finally got something working. I had to make the following changes:

    • got the tables renamed to their default django names (namely, voters_phones instead of voter_phones)

    • found that the foreign keys in voters_phones were int(11) while the primary keys in both voters and phones were bigint(20)

    • removed the join models

    Thanks for your help, guys.