Как отобразить посты по дате их добавления (от новым к старым)? (python, flask)
Всем привет. Я создаю свой первый сайт с блогами на python и flask. Хочу чтобы все посты отображались по дате их публикации от новым к старым. А они у меня отображаются наоборот, от старым к новым.
код функции для отображения постов
@app.route('/posts')
def posts():
posts = Posts.query.order_by(Posts.date_posted)
return render_template('posts.html', posts=posts)
код базы данных взаимодействующий со всеми постами
class Posts(db.Model):
id = db.Column(db.Integer, primary_key=True)
title = db.Column(db.String(255))
content = db.Column(db.Text)
# author = db.Column(db.String(255))
date_posted = db.Column(db.DateTime,
default=datetime.utcnow)
slug = db.Column(db.String(255))
# ключ связующий Юзеров с Постами :)
poster_id = db.Column(db.Integer,
db.ForeignKey('users.id'))
а это html код показывающий посты
{% extends 'base.html' %}
{% block content %}
{% for message in get_flashed_messages() %}
<div class="alert alert-primary alert-dismissible fade show" role="alert">
{{ message }}
<button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
</div>
{% endfor %}
<h1>Blog Posts...</h1>
<br/>
{% for post in posts %}
<div class="shadow p-3 mb-5 bg-body rounded">
<h2>{{ post.title }}</h2>
By: {{ post.poster.username }}<br/>
{{ post.date_posted }}<br/>
{{ post.content|safe }}<br/><br/>
<a href="{{ url_for('post', id=post.id) }}" class="btn btn-outline-secondary btn-sm">View Post</a>
{% if post.poster_id == current_user.id %}
<a href="{{ url_for('edit_post', id=post.id) }}" class="btn btn-outline-secondary btn-sm">Edit Post</a>
<a href="{{ url_for('delete_post', id=post.id) }}" class="btn btn-outline-danger btn-sm">Delete Post</a>
{% endif %}
<br/><br/>
</div>
<br/>
{% endfor %}
{% endblock %}
Так, ну вроде как, все необходимые снипеты предоставил. Буду признателен за помощь.
Ответы (1 шт):
Автор решения: Exord
→ Ссылка
from sqlalchemy import desc
@app.route('/posts')
def posts():
posts = Posts.query.order_by(desc(Posts.date_posted))
return render_template('posts.html', posts=posts)