使用 peewee 和 Python 聚合记录

Aggregate records with peewee and Python

我正在努力学习 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)

关于我的问题: 我想使用求和函数,这就是我遇到问题的地方。我想以 peewee 格式执行此操作 sql:

SELECT SUM(`Logg_Giva_Foder1`) 
FROM mf_logg 
WHERE `Logg_RFID_ID`='752007904107005' AND `Logg_Tid` >= (CURDATE() - INTERVAL 24 HOUR)

在 peewee 文档 (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'>

我希望有人知道如何以正确的方式编写查询。感谢您的帮助。

在这种情况下,注释不是您想要的。而是尝试:

MF_Logg.select(fn.SUM(MF_Logg.Logg_Giva_Foder1)) \
    .where((MF_Logg.Logg_RFID_ID == tag_no) & (MF_Logg.Logg_Tid > timelastday)) \
    .scalar()