我正在使用Jinja模板引擎在Flask中创建一个网站。我有一份公告清单,但没有好办法对它们进行排序。
他们现在正在由id调用的表中。我想先按最新排序(这意味着最高的id)
像:
在我的HTML中,我已经为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>
蟒蛇:
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)
但是那样的话:
无论如何要按降序对它进行排序,不会被网页弄乱?
(我希望我的问题有道理)
答案 0 :(得分:2)
采取gnibbler的建议。我在分页之前重新排序了查询。
更新的代码:
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)