[Fixed]-Many to many relationship in django and templates

1👍

Since your ZoneStage is an intermediate model, the zoneid and stageid should be ForeignKey, not ManyToMany. See example here:

https://docs.djangoproject.com/en/1.8/topics/db/models/#intermediary-manytomany

If you look at your structure, you’ll see that it makes sense. Since your ZoneStage are intersection points, they can’t be many to many. Each ZoneStage will have one unique Zone and one unique Stage.

Once this is done, you could access the values this way for example:

<table border="1">
<tr>
    <td></td>
    <td>{{ object.zone }}</td>
    {% for object in zone|dicsort:"zone_name" %}
        <td>{{ object.zone_name }}</td>
    {% endfor %}
    </tr>
{% for objectS in stage %}
    <tr>
        <td>{{ objectS.stage_no }}</td>
        <td>{{ objectS.stage_name }}</td>
            {% for zonestages in objectS.zonestage_set.all|dictsort:"zoneid.zone_name" %}
                <td>{{ zonestages.zonestage}}</td>
            {% endfor %}
    </tr>
{% endfor %}
</table>

EDIT:

Previous solution works if every intersection has a value. If not one other way to do it would be like this:

<table border="1">
    <tr>
        <td></td>
        <td>{{ object.zone }}</td>
        {% for object in zone|dicsort:"zone_name" %}
            <td>{{ object.zone_name }}</td>
        {% endfor %}
        </tr>
    {% for objectS in stage %}
        <tr>
            <td>{{ objectS.stage_no }}</td>
            <td>{{ objectS.stage_name }}</td>
                {% for zones in zone|dicsort:"zone_name" %}
                    <td>
                    {% for zonestages in objectS.zonestage_set.all %}
                    {% if zonestages.zone == zones %} {{ zonestages.zonestage}}{% endif %}
                    {% endfor %}
                    </td>
                {% endfor %}
        </tr>
    {% endfor %}
    </table>

Leave a comment