Getting an N-N relation in a template
<p>I have these models (an owner can have multiple cars, and a car can have multiple owners):</p>

<pre><code>class Car(models.Model):
    name = models.CharField(max_length=20)

class Owner(models.Model):
    name = models.CharField(max_length=20)

class CarOwner(models.Model):
    car = models.ForeignKey(Car, default = 0, on_delete=Models.CASCADE)
    owner = models.ForeignKey(Owner, default = 0, on_delete=Models.CASCADE)
</code></pre>

<p>and I want to create a template that shows a list of cars with their owners, so I did this:</p>

<pre><code>def cars(request):
   cars = models.Cars.objects.all()
   return render(request, 'template.html', { "cars": cars })
</code></pre>

<p>My <code>template.html</code> is as simple as</p>

<pre><code>{% for car in cars %}
   {{ car.name }} &lt;br&gt;
{% endfor %}
</code></pre>

<p>How can I now refer to all users per car in the <code>template.html</code> file?</p>

<p>CarOwner is the through table of a many-to-many relationship. You should make that explicit:</p>

<pre><code>class Car(models.Model):
    name = models.CharField(max_length=20)
    owners = models.ManyToManyField('Owner', through='CarOwner')
</code></pre>

<p>Now you can do:</p>

<pre><code>{% for car in cars %}
   {{ car.name }} &lt;br&gt;
   {% for owner in car.owners.all %}
       {{ owner.name }}
    {% endfor %}
{% endfor %}
</code></pre>

python django