简体   繁体   中英

Sorting A List In Descending Order Jinja

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)

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM