﻿id	summary	reporter	owner	description	type	status	component	version	severity	resolution	keywords	cc	stage	has_patch	needs_docs	needs_tests	needs_better_patch	easy	ui_ux
33772	Queryset first() returns different result than queryset[0] when using ExpressionWrapper	Pablo Pissi	Pablo Pissi	"Hi! I was creating a new app and found the following scenario, seems like an issue to me:

I have three models: 
{{{
class Transaction(models.Model):
    amount = models.DecimalField(max_digits=10, decimal_places=2)
    description = models.CharField(max_length=255)
    created_by = models.ForeignKey(get_user_model(), on_delete=models.CASCADE, related_name=""created_transactions"")
    created_at = models.DateTimeField(auto_now_add=True)


class TransactionUser(models.Model):
    user = models.ForeignKey(get_user_model(), on_delete=models.CASCADE, related_name=""transactions"")
    transaction = models.ForeignKey(""bills.Transaction"", on_delete=models.CASCADE, related_name=""users"")
    amount = models.DecimalField(max_digits=10, decimal_places=2)
    transaction_type = models.ForeignKey('bills.TransactionType', on_delete=models.PROTECT)


class TransactionType(models.Model):
    name = models.CharField(max_length=50)
    code = models.CharField(max_length=3)
    multiplier = models.DecimalField(max_digits=5, decimal_places=2)

}}}

I create the following instances:
{{{
        transaction = Transaction(amount=100)
        positive = TransactionType(multiplier=1)
        negative = TransactionType(multiplier=-1)
        
        TransactionUser(transaction=transaction, user=user1, amount=50, transaction_type=negative)
        TransactionUser(transaction=transaction, user=user2, amount=50, transaction_type=negative)
        TransactionUser(transaction=transaction, user=user1, amount=10, transaction_type=positive)

}}}
I want to obtain the balance of each transaction by doing the following query:

{{{
 TransactionUser.objects \
        .filter(user_id=user_id) \
        .annotate(
            real_amount=ExpressionWrapper(F(""amount"")*F(""transaction_type__multiplier""), output_field=DecimalField()),
        ).values(""transaction"") \
        .annotate(
            balance=Sum(""real_amount"")
        )
}}}
If I log the queryset returned, the value logged is:

{{{
<QuerySet [{'transaction': 1, 'balance': Decimal('-40.0000')}]>
}}}

But if I log 
{{{
queryset.first()[""balance""]
>>> -50
}}}
And if I log
{{{
queryset[0][""balance""]
>>> -40
}}}

It's also reproducible in 4.0"	Cleanup/optimization	closed	Database layer (models, ORM)	3.2	Normal	fixed	ExpressionWrapper,first,queryset		Ready for checkin	1	0	0	0	0	0
