Sorting A List In Descending Order Jinja


Question

I'm creating a website in Flask using the Jinja template engine. I have a list of announcements but no good way to sort them.

They are in a table being called on by id right now. I want to sort it by newest first (which would mean the highest id)

Like:

  • P1
    • 5
    • 4
    • 3
  • P2
    • 2
    • 1

In my HTML I have put this instruction for Jinja:

<div id="main"> 

{% autoescape false %}
{% for announcement in announcements.items|sort(attribute='id', reverse = True) %}

  <a name={{announcement.title}}></a>
  <h1>{{announcement.title}} - Posted on: {{announcement.date}}</h1>
  {{announcement.body}}
  <br/>
  <hr/>

{% endfor %}
{% endautoescape %}

 <p class = "footer">{% if announcements.has_prev %}<a href="{{ url_for('index', page = announcements.prev_num) }}"><< Newer posts</a>{% else %}<< Newer posts{% endif %} | 
 {% if announcements.has_next %}<a href="{{ url_for('index', page = announcements.next_num) }}">Older posts >></a>{% else %}Older posts >>{% endif %} </p>

<br/>
</div>

And the python:

from flask import render_template, Markup
from app import app
from config import POSTS_PER_PAGE
from models import Announcement, VideoAnnouncement

@app.route('/')
@app.route('/index')
@app.route('/index/<int:page>')
def index(page = 1):
    loggedOut = True
    announcements = Announcement.query.paginate(page, POSTS_PER_PAGE, True)
    videoAnnounce = VideoAnnouncement.query.all()
    return render_template("index.html", announcements = announcements, videoAnnouncements = videoAnnounce , loggedOut = loggedOut)

But that sorts like this:

  • P1
    • 3
    • 2
    • 1
  • P2
    • 5
    • 4

Is there anyway to sort it in descending order that won't get messed up by the pages?

(I hope my question made sense)

1
3
10/28/2012 10:40:31 PM

Accepted Answer

Taking gnibbler's advice. I re-ordered the query before pagination.

Updated code:

from flask import render_template, Markup
from app import app
from config import POSTS_PER_PAGE
from models import Announcement, VideoAnnouncement

@app.route('/')
@app.route('/index')
@app.route('/index/<int:page>')
def index(page = 1):
    loggedOut = True
    query = Announcement.query.order_by(Announcement.id.desc())
    announcements = query.paginate(page, POSTS_PER_PAGE, True)
    videoAnnounce = VideoAnnouncement.query.all()
    return render_template("index.html", announcements = announcements, videoAnnouncements = videoAnnounce , loggedOut = loggedOut)
2
10/28/2012 11:57:06 PM

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Icon