Skip to content


Subversion checkout URL

You can clone with
Download ZIP


Groupby Ordering #27

PhilipCammarata opened this Issue · 3 comments

4 participants


Sorry if I am missing something but when using Flask/SQLAlchemy to query the database for a list of bookmarks and their categories I get some strange ordering.

<section class="span-12" id="category-bookmarks">
{% for category in category_bookmarks|groupby('category') %}
    <h2>{{ category.grouper.title }}</h2>
        {% for bookmark in category.list %}
        <li><img src="static/favicons/{{ bookmark.favicon }}" /><a href="{{ bookmark.url }}">{{ bookmark.title|trim }}</a></li>
        {% endfor %}
{% endfor %}

Category is a foreign_key and this does work but every time I reload the page my categories are displayed in what looks to me like a random order. I pull the bookmarks via a SQLAlchemy call:

category_bookmarks = Bookmark.query.order_by(db.desc('created'))

How can I control how groupby orders my results? Putting a |sort after

for category in category_bookmarks|groupby('category')

doesn't seem to effect it.


The groupby filter, sorts the iterable always by the given grouper. That is required by Python's itertools.groupby function, which is used under the hood.


@wallunit what if I already have a collection sorted by the key, but in a very specific order and I just want to group items in the collection without loosing the order? I'm using itertools.groupby a lot and I very much like that it doesn't do the sorting for me and does only what it should do.

I've used Jinja2's groupby for the first time today and I was very surprised that I've lost my sort order.


Sorting before calling groupby covers the majority of cases... if it doesn't fit yours, you can always register the original itertools function as a global.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Something went wrong with that request. Please try again.