也就是降序排序
简单使用
questions = Questions.query.order_by(Questions.time.desc()).all()
设置默认排序
如果几乎所有的questions都是按照时间降序排序,总不能每一条语句都加上order_by(Questions.time.desc())
所以设置默认排序是有效的
1class Questions(db.Model):
2 __tablename__ = 'questions'
3 id = db.Column(db.Integer, primary_key=True)
4 title = db.Column(db.String(50), nullable=False)
5 content = db.Column(db.Text, nullable=False)
6 time = db.Column(db.DateTime, nullable=False)
7
8 __mapper_args__ = {
9 "order_by": time.desc()
10 }
如代码所示,使用__mapper_args__就可,__mapper_args__可以做很多事,具体看这里
设置默认排序下面的做法是错误的
1 __mapper_args__ = {
2 "order_by": 'Questions.time.desc()'
3 }
4 # 或者
5 __mapper_args__ = {
6 "order_by": 'Questions.time desc'
7 }
8 # 或者
9 __mapper_args__ = {
10 "order_by": 'desc(Questions.time)'
11 }
多对多默认排序
比如这样
1question = Questions.query.filter_by(id=1).first()
2for reply in question.replies:
3 print(reply.content)
又如何设置回复是按照回复时间排序的
总不能这样
1for reply in sorted(question.replies):
2# 这会报错的
3TypeError: unorderable types: Replies() < Replies()
怎么设置
1replies = db.relationship('Questions',
2 backref=db.backref('replies',
3 lazy='dynamic',
4 order_by='Replies.time')
ok,暂时这样
知识共享署名-非商业性使用-相同方式共享4.0国际许可协议