gpt4 book ai didi

python - 按降序对列表进行排序 Jinja

转载 作者:可可西里 更新时间:2023-11-01 13:37:28 26 4
gpt4 key购买 nike

我正在使用 Jinja 模板引擎在 Flask 中创建一个网站。我有一个公告列表,但没有好的方法来对它们进行排序。

他们现在在一个由 id 调用的表中。我想按最新排序(这意味着最高 ID)

喜欢:

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

在我的 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>

还有 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)

但那是这样的:

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

有没有办法降序排列又不会被页面弄乱?

(我希望我的问题是有道理的)

最佳答案

采纳 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)

关于python - 按降序对列表进行排序 Jinja,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13113754/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com