按日期时间间隔筛选 SQLAlchemy 中的以下查询



我创建了一个连接到Postgres数据库的烧瓶API,i 我正在尝试创建一个路由,该路由将为我提供数据库中的历史数据,以便我可以接收一个 JSON 以图表的形式显示在前端 (ReactJS) 上。

现在,我有以下查询在pgAdmin上成功运行:

SELECT humidity, temperature, "waterpumpState", "dateTime" from public."systemInformation"  where "systemInformation"."dateTime" > current_date - interval '7 days'

我用SQLAlchemy创建了这个数据库模型:

class statusInformation(db.Model):
__tablename__ = 'systemInformation'
id = db.Column(db.Integer, unique=True, primary_key=True)
humidity = db.Column(db.Float, nullable=False)
temperature = db.Column(db.Float, nullable=False)
waterpumpState = db.Column(db.Boolean, nullable=False)
clientOverride = db.Column(db.Boolean, nullable=False)
humidityLevelSetting = db.Column((db.String(250)))
dateTime = db.Column(db.TIMESTAMP, server_default=db.func.current_timestamp(), nullable=False)

从此表中,我只想使用 SQLAlchemy 查询提取湿度、温度和日期时间。

我想获取从这一刻起不超过 7 天的所有条目,以便我可以将它们映射到调用此路由时显示的 JSON,响应我想创建一个 ReactJS 图表,显示 7 天的湿度和温度水平。

这是我尝试使用datetime在python中使用SQLAlchemy做的事情:

def get_historic_data():
now = datetime.now()
seven_days_ago = now - timedelta(days=7)
historicData = statusInformation.query.filter(statusInformation.dateTime >= seven_days_ago)
return statusInformation.historyDetailedInformationJson(historicData) 

历史详细信息Json只是JSON的一个模板,应该回到我身边,它看起来像这样:

def historyDetailedInformationJson(self):
return{
'humidity':self.humidity,
'temperature':self.temperature,
'waterpumpState':self.waterpumpState,
'dateTime':self.dateTime
}

这是我尝试打印get_historic_data的结果时得到的:

SELECT "systemInformation".id AS "systemInformation_id", "systemInformation".emInformation".temperature AS "systemInformation_temperature", "systemInformaterpumpState", "systemInformation"."clientOverride" AS "systemInformation_clilSetting" AS "systemInformation_humidityLevelSetting", "systemInformation"."d
FROM "systemInformation"
WHERE "systemInformation"."dateTime" >= %(dateTime_1)s

如果有人能帮助我澄清这个问题,我将不胜感激。 谢谢。

statusInformation.query.filter(statusInformation.dateTime >= seven_days_ago)将生成一个Query对象,您可以使用过滤器等增量构建查询,但您需要指定实际执行查询的结果形式。

例如(假设statusInformation是一个SQLAlchemy ORM模型)如果historicData是你的查询对象,那么historicData.all()将返回查询返回的行作为对象列表。如果只期望一个结果,则historicData.one()将返回单个对象,并在查询结果中实际上存在多行时引发异常。

如果您检查查询文档,还有其他方法可以通过其他方式解决查询(例如one_or_none()count())。

最新更新