【问题标题】:Aggregate records with peewee and Python使用 peewee 和 Python 聚合记录
【发布时间】:2015-05-04 23:40:50
【问题描述】:

我正在尝试学习 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'>

我希望有人知道如何以正确的方式编写查询。任何帮助表示赞赏。

【问题讨论】:

    标签: python mysql peewee


    【解决方案1】:

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

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

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2023-03-26
    • 1970-01-01
    • 2017-09-05
    • 1970-01-01
    • 2023-03-05
    • 2020-07-03
    • 2015-02-11
    相关资源
    最近更新 更多