You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用fn.MAX与别名的Peewee查询报“无此属性”,如何访问结果?

How to Access Fields in Your Peewee Aggregation Query

Hey there! Let's break down why you're seeing that "no such attribute" error and how to fix it.

First, let's clarify what your query is doing: you're running a projection query (selecting specific fields/aggregates instead of full model instances) that joins Transaction and User, grabs the maximum transaction amount, and pairs it with the associated user's name. The issue here is that Peewee doesn't return a full Transaction or User model instance for this kind of query—instead, it returns a lightweight result object with just the fields you selected.

Correct Way to Access the Fields

  1. First, fetch the result properly
    Since you used limit(1), use .first() to get the single result (it returns None if there are no matches, which is safer than .get() which raises an exception if no rows exist):

    result = toptx24h.first()
    
  2. Access the fields directly via their alias/name
    You aliased the aggregate as amount, and selected User.user_name directly. So you can access these as attributes on the result object:

    if result:  # Always check if result exists to avoid AttributeError on None
        max_transaction_amount = result.amount
        associated_user_name = result.user_name
        print(f"Max amount: {max_transaction_amount}, User: {associated_user_name}")
    else:
        print("No transactions found in the time range.")
    

Optional: Make It More Explicit With Aliases

To avoid any confusion (especially if you have overlapping field names across models), you can alias the user_name field too:

toptx24h = Transaction.select(
    fn.MAX(Transaction.amount).alias('max_amount'),
    User.user_name.alias('user_name')
).join(
    User, on=(User.wallet_address == Transaction.source_address)
).where(
    Transaction.created > past_dt
).limit(1)

# Then access like this:
if result:
    print(result.max_amount, result.user_name)

Why You Got the Error

Chances are you were trying to access fields through the model classes (e.g., result.transaction.amount or result.user.user_name), assuming the result was a full model instance. But since you only selected specific fields, Peewee doesn't populate those model attributes—you have to access the selected fields directly by their alias/name.

内容的提问来源于stack exchange,提问作者bbedward

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.21 06:33:50