How to sum the annotation results

hello, this is my model

class Order(models.Model):
    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name="order_user")
    first_name = models.CharField(_('first name'), max_length=50)
    last_name = models.CharField(_('last name'), max_length=50)
    email = models.EmailField(_('e-mail'))
    address = models.CharField(_('address'), max_length=250)
    created = models.DateTimeField(auto_now_add=True)
    updated = models.DateTimeField(auto_now=True)

class OrderItem(models.Model):
   id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
   order = models.ForeignKey(Order, related_name='items', on_delete=models.CASCADE)
   product = models.ForeignKey(Product, related_name='order_items', on_delete=models.CASCADE)
   shop = models.ForeignKey(MyShop, related_name='shop_order', on_delete=models.CASCADE)
   price = models.DecimalField(max_digits=10, decimal_places=2)
   quantity = models.PositiveIntegerField(default=1)```


this is my view:

def shop_orders(request):
    orders = Order.objects.prefetch_related(
        Prefetch(
            'items',
         queryset=OrderItem.objects.filter(shop=request.user.user_profile_shop).annotate(ord_total=ExpressionWrapper(
        F('price') * F('quantity'), output_field=DecimalField())).select_related('shop'),
            to_attr='items_from_specific_shop'
        )
    )
    return render(request, 'account/paneli/shop/orders/shop_orders.html', {'orders': orders,})

how can i sum all items(ord_total) for each order

Hi MarcoItalia92,

I think you need to wrap the ExpressionWrapper that does the multiplication and type coercion with Sum

OrderItem.objects.annotate(ord_total=Sum(ExpressionWrapper(F('price') * F('quantity'), output_field=DecimalField())))

Thanks for the reply, Unfortunately not, order has many items, the ord_total is annotate the total price per quantity for each item, I want annotate the total sum of all items in this order

You’re right. It should be a Sum annotation on the Order queryset.

    Order.objects.annotate(
        order_total=Sum(ExpressionWrapper(
        F('price') * F('quantity'), output_field=DecimalField())),
    ).prefetch_related(
        Prefetch(
            'items',
            queryset=OrderItem.objects.filter(shop=request.user.user_profile_shop).annotate(ord_total=ExpressionWrapper(
        F('price') * F('quantity'), output_field=DecimalField())).select_related('shop'),
            to_attr='items_from_specific_shop'
        )
    )

Solved, thanky very much