我有这个查询,试图查找给定日期和状态的记录:
ld=LunchDay.query.filter(and_(func.DATE(LunchDay.timestamp == datetime.date.today()), LunchDay.status==1))
模型:
class LunchDay(db.Model):
__tablename__ = 'lunch_day'
id = db.Column(db.Integer, primary_key=True)
user_id = db.Column(db.Integer, db.ForeignKey('user.id'))
user = relationship("User", foreign_keys=[user_id])
timestamp = db.Column(db.DateTime, index=True, default=datetime.today())
status = db.Column(db.Integer)
它运行并且没有引发错误,但似乎不考虑日期。它将在数据库的DateTimeField中找到日期为昨天的条目:
2018-11-13 00:00:00.000000
这是昨天的日期,但是它只是根据状态来选择它,就像将其视为“或”一样。我使用的导入是:
from sqlalchemy import func, and_
答案 0 :(得分:1)
打印出查询所生成的实际sql,以查看发生了什么。例如:
ld=LunchDay.query.filter(and_(func.DATE(LunchDay.timestamp == datetime.date.today()), LunchDay.status==1))
print(ld)
打印:
SELECT lunch_day.id AS lunch_day_id, lunch_day.timestamp AS lunch_day_timestamp, lunch_day.status AS lunch_day_status
FROM lunch_day
WHERE DATE(lunch_day.timestamp = %(timestamp_1)s) AND lunch_day.status = %(status_1)s
您可以看到lunch_day.timestamp
和参数timestamp_1
的相等性正在传递给DATE
函数。
在您的sqlalchemy查询中func.DATE(LunchDay.timestamp == datetime.date.today())
实际上很容易看到。我假设您想将LunchDay.timestamp
转换为日期,然后然后将其与应该为datetime.date.today()
的{{1}}进行比较。
db.func.DATE(LunchDay.timestamp) == date.today()
打印:
print(LunchDay.query.filter(and_(func.DATE(LunchDay.timestamp) == datetime.date.today(), LunchDay.status == 1)))
要注意的另一件事是,传递到SELECT lunch_day.id AS lunch_day_id, lunch_day.timestamp AS lunch_day_timestamp, lunch_day.status AS lunch_day_status
FROM lunch_day
WHERE DATE(lunch_day.timestamp) = %(DATE_1)s AND lunch_day.status = %(status_1)s
的多个语句会自动被视为filter()
,因此您可以通过删除以下内容来简化查询:
and_()