How can I do multiple “order_by” in Flask-SQLAlchemy?

后端 未结 3 558
野性不改
野性不改 2021-02-03 16:58

Let\'s say I have a User model with fields popularity and date_created. I want to do the following query:

SELECT * FROM us         


        
相关标签:
3条回答
  • 2021-02-03 17:38

    What you also could do:

    from sqlalchemy import and_, or_
    User.query.order_by(and_(User.popularity.desc(), User.date_created.desc())).all()
    

    Note: and_ and or_ are coming from the sqlalchemy library and not from flask_sqlalchemy library. sqlalchemy is a dependency for flask_sqlalchemy, so you should be good.

    LTS: You can mix sqlalchemy lib with flask_alchemy lib

    0 讨论(0)
  • 2021-02-03 17:44

    I have another example:

    user = User.query.order_by(User.id.desc()).limit(10).all()
    
    s.t
    

    User is my class db.Modle

    0 讨论(0)
  • 2021-02-03 17:47

    This should work

    User.query.order_by(User.popularity.desc(),User.date_created.desc()).limit(10).all()
    
    0 讨论(0)
提交回复
热议问题