robmathers robmathers - 29 days ago 17
Python Question

Use Jinja's groupby filter with tuples

I'm building a Flask app with Jinja2 templates and feeding it data from Flask-SQLAlchemy. I want to build a view (list effectively) based on a query that gives me a tuple with two objects (

User
and
Registration
):

eligible_racers = db.session.query(User, Registration).filter(User.id==Registration.racer_id).filter(Registration.team_id==team_id).filter(Registration.season_id==race.season_id).all()


In my template I'd like to group the results by an attribute of the
Registration
object. The
grouby
filter seems ideal, but it doesn't seem like there's a way to pass it an attribute of one of the tuple members.

Is there an elegant way to do this in my template? Or do I need to do the grouping in my Python view code and pass the template differently structured data (keeping in mind I need to keep the users and registrations paired)?

Answer

Some Jinja filters, including groupby, handle multiple levels of attribute lookup by separating the attributes with .. SQLAlchemy queries returned keyed tuples with the name of the selectable (the model in this case) as the attribute name.

{% for level, items in racers|groupby('Registration.level') %}
    {{ level }}
    {% for user, registration in items %}
        {{ user.name }}
    {% endfor %}
{% endfor %}

You could also use 1.level, index lookup works too.