Search code examples
python-3.xsqlitepeewee

Python/Peewee query with fn.MAX and alias results in "no such attribute"


I have a peewee query that looks like this:

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

My understanding is this should be equivalent to:

select MAX(t.amount) as amount, u.user_name from transaction t inner join user u on u.wallet_address = t.source_address where transaction.created > past_dt limit 1

My question is how to I access the results user_name and amount

When I try this, I get an error saying top has no attribute named amount

for top in toptx24h:
    top.amount # No such attribute amount

I'm just wondering how i can access the amount and user_name from the select query.

Thanks


Solution

  • I think you need a GROUP BY clause to ensure you're grouping by User.username.

    I wrote some test code and confirmed it's working:

        with self.database.atomic():
            charlie = TUser.create(username='charlie')
            huey = TUser.create(username='huey')
    
            data = (
                (charlie, 10.),
                (charlie, 20.),
                (charlie, 30.),
                (huey, 1.5),
                (huey, 2.5))
            for user, amount in data:
                Transaction.create(user=user, amount=amount)
    
        amount = fn.MAX(Transaction.amount).alias('amount')
        query = (Transaction
                 .select(amount, TUser.username)
                 .join(TUser)
                 .group_by(TUser.username)
                 .order_by(TUser.username))
        with self.assertQueryCount(1):
            data = [(txn.amount, txn.user.username) for txn in query]
    
        self.assertEqual(data, [
            (30., 'charlie'),
            (2.5, 'huey')])