使用fn.MAX与别名的Peewee查询报“无此属性”,如何访问结果?
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
First, fetch the result properly
Since you usedlimit(1), use.first()to get the single result (it returnsNoneif there are no matches, which is safer than.get()which raises an exception if no rows exist):result = toptx24h.first()Access the fields directly via their alias/name
You aliased the aggregate asamount, and selectedUser.user_namedirectly. 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

