Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP

Loading…

Groupby Ordering #27

Open
PhilipCammarata opened this Issue · 3 comments

4 participants

@PhilipCammarata

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>
    <ul>
        {% for bookmark in category.list %}
        <li><img src="static/favicons/{{ bookmark.favicon }}" /><a href="{{ bookmark.url }}">{{ bookmark.title|trim }}</a></li>
        {% endfor %}
    </ul>
{% endfor %}
</section>

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.

@snoack

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.

@yawor

@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.

@untitaker
Collaborator

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.