Flask-sqlalchemy query datetime intervals

前端 未结 4 524
南笙
南笙 2021-01-12 20:57

I have defined a table with flask-sqlalchemy. Displayed below.

class Notes(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    notes = db.Column(         


        
4条回答
  •  清歌不尽
    2021-01-12 21:22

    The following should also work:

    from sqlalchemy import func
    from sqlalchemy.dialects.postgresql import INTERVAL
    from sqlalchemy.sql.functions import concat
    
    Notes.query\
        .filter(
            Notes.added_at >= (func.now() - func.cast(concat(8, ' HOURS'), INTERVAL))
        )\
        .limit(num)
    

    It has the nice property that 8 can be replaced with a value from inside the database, e.g., if you joined in another table with dynamic intervals. I gave this answer also here.

提交回复
热议问题