折腾:
[已解决]Flask中对于SQLAlachemy中检索特定时间内的条目
期间,用代码:
currentUsers = User.query.all() app.logger.debug(‘currentUsers=%s’, currentUsers) currentUsersCount = len(currentUsers) app.logger.debug(‘currentUsersCount=%s’, currentUsersCount) #todayEventList = Event.query.filter_by(user_openid = curUser.openid).all() dateToday = datetime.today() app.logger.debug(“type(dateToday)=%s, dateToday=%s”, type(dateToday), dateToday) todayEventList = Event.query.filter_by(and_(user_openid=curUser.openid, start_date.date() = dateToday)).all() app.logger.debug(“todayEventList=%s”, todayEventList) |
结果出错:
File “/root/html/SIPEvents/sipevents/views.py”, line 378 todayEventList = Event.query.filter_by(and_(user_openid=curUser.openid, start_date.date() = dateToday)).all() SyntaxError: keyword can’t be an expression |
搜:
sqlalchemy SyntaxError: keyword can’t be an expression
SQLAlchemy Expression Language, Advanced Usage | Python Central
SyntaxError: keyword can’t be an expression – Google Groups
sqlAlchemy and update table – Google Groups
SyntaxError: keyword can’t be an expression | Treehouse Community
python – 请问用sqlalchemy如何根据中文字段名做查询? – SegmentFault
python – SQLAlchemy中模糊查询,如何like多个关键字 – SegmentFault
python – How to use SQLAlchemy to select value at a position in a PostgreSQL ARRAY? – Stack Overflow
[总结]
此处,对于代码出的错,是无法解决的
-》SQLAlchemy中的query的filter中,就是不支持表达式,只支持column的名字判断而已。
-》最后只好放弃:
在query查询期间,传入表的列的属性,即属于对应的表达式
只能传入表的某个列的名字了
-》最后为了判断是非是当天,无法直接判断datetime的date,而只能去曲线救国,通过判断日期时间是否在今天的时间的范围内去判断:
dateFormat = “%Y-%m-%d” timeFormat = “%H:%M:%S” datetimeFormat = dateFormat + ” ” + timeFormat app.logger.debug(‘dateFormat=%s, timeFormat=%s, datetimeFormat=%s’, dateFormat, timeFormat, datetimeFormat) todayDatetime = datetime.today() todayDate = date.today() #todayDateStr = todayDatetime.strftime(dateFormat) todayDateStr = todayDate.strftime(dateFormat) app.logger.debug(‘todayDate=%s, todayDateStr=%s’, todayDate, todayDateStr) todayStartStr = todayDateStr + ” 00:00:00″ todayEndStr = todayDateStr + ” 23:59:59″ app.logger.debug(‘todayStartStr=%s, todayEndStr=%s’, todayStartStr, todayEndStr) todayStart = datetime.strptime(todayStartStr, datetimeFormat) todayEnd = datetime.strptime(todayEndStr, datetimeFormat) app.logger.debug(‘todayStart=%s, todayEnd=%s’, todayStart, todayEnd) todayEventList = Event.query.filter(and_(Event.user_openid == curUser.openid, Event.start_date >= todayStart, Event.start_date <= todayEnd)).all() |
-》
后来看到了:
datetime – Make Sqlalchemy Use Date In Filter Using Postgresql – Stack Overflow
from sqlalchemy import Date, cast from datetime import date my_data = session.query(MyObject).\ filter(cast(MyObject.date_time,Date) == date.today()).all() |
-》好像也是可以实现:
直接比较datetime的date的
不过以后有空再去试试吧。
转载请注明:在路上 » [已解决]SQLAlchemy中查询出错:SyntaxError: keyword can’t be an expression