我有以下两种型号:
class Company(db.Model):
__tablename__ = "company"
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String(128), index=True, unique=True, nullable=False)
comments = db.relationship("Comment", backref="comment", lazy=True)
class Comment(db.Model):
__tablename__ = "comment"
id = db.Column(db.Integer, primary_key=True)
company_id = db.Column(db.Integer, db.ForeignKey("company.id"), nullable=False)
body = db.Column(db.Text)
created_datetime = db.Column(
db.TIMESTAMP(timezone=True), default=datetime.datetime.now
)
以及以下Jinja2模板:
{% for comment in company.comments %}
<div><span>{{ comment.created_datetime }}:</span> {{comment.body}}</div>
{% endfor %}
我想按created_datetime desc排序评论。
我可以在Jinja2模板中这样做吗?
答案 0 :(得分:1)
在Jinja2中:
升序
{% for comment in company.comments|sort(attribute='created_datetime') %}
<div><span>{{ comment.created_datetime }}:</span> {{comment.body}}</div>
{% endfor %}
下降
{% for comment in company.comments|sort(attribute='created_datetime', reverse = True) %}
<div><span>{{ comment.created_datetime }}:</span> {{comment.body}}</div>
{% endfor %}
或者在将company
传递给模板之前用Python进行排序:
@app.route('/')
def index():
# e.g company 10
company = Company.query.join(Company.comments).filter(Company.id == 10).order_by(Comment.created_datetime.desc()).first_or_404()
render_template('index.html', company=company)