Chris
Chris

Reputation: 527

django display specific data from model in templates

Model:

class Exercise (models.Model):
    name_e = models.CharField(max_length=50)

class Subject (models.Model):
    name_s = models.CharField(max_length=50)
    exercise = models.ForeignKey(Exercise)

View:

exercise_all = Exercise.objects.all()
subject_all = Subject.objects.all()

My SQL table contain subjects and exercises connected via ForeignKey

I pass view variables as a context to the template:

{% for e_field in exercise_all %}
<table>
<tr><th>Header</th></tr>
    {% for s_field in subject_all %}
    <tr><td>{{ e_field.name_e }}</td></tr>
    {% endfor %}
</table>
{% endfor %}

If I have, let's say, 3 types of Exercises and 10 Subjects connected with Exercises (subject1->exercise1, subject2->exercise1, subject3->exercise1, subject4->exercise2 etc.) I want to display 3 tables in a template and each table will display only tr/subjects corresponding to table/exercise. I tried with {% if ... in ... %} but maybe i should do some function in view.

Upvotes: 1

Views: 2073

Answers (1)

user234932
user234932

Reputation:

In this case you should be able to say:

{% for e_field in exercise_all %}
<table>
<tr><th>Header</th></tr>
    {% for s_field in e_field.subject_set.all %}
    <tr><td>{{ e_field.name_e }}</td></tr>
    {% endfor %}
</table>
{% endfor %}

Upvotes: 2

Related Questions