关于sqlalchemy的desc


也就是降序排序

简单使用

questions = Questions.query.order_by(Questions.time.desc()).all()

设置默认排序

如果几乎所有的questions都是按照时间降序排序,总不能每一条语句都加上order_by(Questions.time.desc())
所以设置默认排序是有效的

class Questions(db.Model):
    __tablename__ = 'questions'
    id = db.Column(db.Integer, primary_key=True)
    title = db.Column(db.String(50), nullable=False)
    content = db.Column(db.Text, nullable=False)
    time = db.Column(db.DateTime, nullable=False)

    __mapper_args__ = {
        "order_by": time.desc()
    }

如代码所示,使用__mapper_args__就可,__mapper_args__可以做很多事,具体看这里
设置默认排序下面的做法是错误

    __mapper_args__ = {
        "order_by": 'Questions.time.desc()'
    }
    # 或者
    __mapper_args__ = {
        "order_by": 'Questions.time desc'
    }
    # 或者
    __mapper_args__ = {
        "order_by": 'desc(Questions.time)'
    }

多对多默认排序

比如这样

question = Questions.query.filter_by(id=1).first()
for reply in question.replies:
    print(reply.content)

又如何设置回复是按照回复时间排序的
总不能这样

for reply in sorted(question.replies):
# 这会报错的
TypeError: unorderable types: Replies() < Replies()

怎么设置

replies = db.relationship('Questions',
                          backref=db.backref('replies',
                                             lazy='dynamic',
                                             order_by='Replies.time')

ok,暂时这样

Comments !