Skip to content Skip to sidebar Skip to footer

How To Loop Through Related Tables With Jinja2?

Description I am learning Flask and I created a database which contains 3 tables which are related between them: Company: info about the company I worked for (made up :) ) Job: in

Solution 1:

I was able to achive my goal in this (NON ELEGANT) way. First of all I queried all the content from all the tables and placed them as an input variable for the html rendering:

c = Company.query.all()
r = Role.query.all()
t = Task.query.all()

@app.route('/working_experience')defwork():
   return render_template('working_experience.html', c=c, r=r, t=t)

Then I added the Jinja nested for loops like so:

{% for company in c %}
    <h2>{{ company.name }}</h2><ul>
    {% for role in r %}
        {% if company.id == role.company_id %}
            <li><h6>{{ role.position }}</h6></li><ul>
            {% for task in t %}
                {% if role.id == task.role_id %}
                    <li><h6>{{ task.description }}</h6></li>
                {% endif %} 
            {% endfor %}
            </ul>
        {% endif %} 
    {% endfor %}
    </ul><hr>

{% endfor %}

If you are aware of a better solution please let me know and I woudl really apreciate it!

Post a Comment for "How To Loop Through Related Tables With Jinja2?"