我正在尝试学习Python,并且有理解如何使用peewee的聚合函数。
在我的代码中,我首先执行以下导入:
import sys
from datetime import datetime, timedelta
from peewee import *
from database import (db_init, MF_Djur, MF_Logg, MF_Senaste_Koll, MF_Foderspec)
为了测试peewee和数据库连接是否有效,我成功使用了以下代码:
antalgivor24h = MF_Logg.select() \
.where((MF_Logg.Logg_RFID_ID == tag_no) & (MF_Logg.Logg_Tid > timelastday)).count()
print(antalgivor24h)
对我的问题:我想使用sum函数,这就是我遇到问题的地方。我想用peewee格式做这个sql:
SELECT SUM(`Logg_Giva_Foder1`)
FROM mf_logg
WHERE `Logg_RFID_ID`='752007904107005' AND `Logg_Tid` >= (CURDATE() - INTERVAL 24 HOUR)
在peewee docs(http://peewee.readthedocs.org/en/latest/peewee/querying.html#aggregating-records)中,我看到了以下示例代码:
query = (User
.select()
.annotate(
Tweet,
fn.Max(Tweet.created_date).alias('latest_tweet_date')))
基于此,我尝试了:
totalgiva124h = MF_Logg.select() \
.where((MF_Logg.Logg_RFID_ID == tag_no) & (MF_Logg.Logg_Tid > timelastday)) \
.annotate(MF_Logg, fn.Sum(MF_Logg.Logg_Giva_Foder1))
此代码给出了以下错误:
Traceback (most recent call last):
File "testscript.py", line 32, in <module>
.annotate(MF_Logg, fn.Sum(MF_Logg.Logg_Giva_Foder1))
NameError: name 'fn' is not defined
我已经搜索了这个错误但是对于peewee聚合记录我得不到多少帮助(对于一般的Python名称错误,我发现了很多,但没有任何帮助我)。但是,在一个页面上我读到它可以帮助分别导入peewee fn。因此我尝试添加
from peewee import *, fn
然后我收到以下错误,所以没有运气:
Traceback (most recent call last):
File "testscript.py", line 32, in <module>
.annotate(MF_Logg, fn.Sum(MF_Logg.Logg_Giva_Foder1))
File "/usr/local/lib/python2.7/dist-packages/peewee.py", line 1763, in annotate
query = query.ensure_join(query._query_ctx, rel_model)
File "/usr/local/lib/python2.7/dist-packages/peewee.py", line 1522, in ensure_join
query = self.switch(lm).join(rm, on=on).switch(ctx)
File "/usr/local/lib/python2.7/dist-packages/peewee.py", line 199, in inner
func(clone, *args, **kwargs)
File "/usr/local/lib/python2.7/dist-packages/peewee.py", line 1505, in join
self._query_ctx, model_class))
ValueError: No foreign key between <class 'database.MF_Logg'> and <class 'database.MF_Logg'>
我希望有人知道如何以正确的方式编写查询。任何帮助表示赞赏。
答案 0 :(得分:2)
在这种情况下,Annotate不是您想要的。而是尝试:
ReportViewer1.LocalReport.Refresh()
ReportViewer1.RefreshReport()