简体   繁体   中英

Compare DateTime and Interval in SQLAlchemy

I have this class:

class Monitor(db.Model):
    '''
    Base Monitor class.
    '''
    __tablename__ = 'monitor'
    id = db.Column(db.Integer(), primary_key=True)
    last_checked = db.Column(db.DateTime(timezone=False))
    poll_interval = db.Column(db.Interval(),
                              default=datetime.timedelta(seconds=300))

And I have this query where I attempt to return only objects that haven't been checked since (now - interval):

monitors = db.session.query(Monitor).\
           filter(or_(Monitor.last_checked < (datetime.utcnow() - Monitor.poll_interval)),
                      Monitor.last_checked == None).\
           all()

But the query returns nothing. I'm having a hard time figuring out the proper way to do this. Am I on the right track or am I missing something? I'm using MySQL as the database.

Your parenthesis are wrong. I believe what you want is:

monitors = db.session.query(Monitor).\
       filter(or_(Monitor.last_checked < (datetime.utcnow() - Monitor.poll_interval),
                  Monitor.last_checked == None)).\
       all()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM