Skip to content Skip to sidebar Skip to footer

Django Sum Of Multiplied Values

I am trying to show the total weight of assets I have presented on a table. Each Asset has a weight and a quantity and I can present the total weight of each asset as below: def by

Solution 1:

You could use the ExpressionWrapper()(mostly Django 1.8+)

assets = Asset.objects.all().annotate(
    total_weight=ExpressionWrapper(F('asset_quantity') * F('asset_weight'), 
                                   output_field=IntegerField() ))

That should give you the total weight for each object, i.e. quantity times weight.

Now, you should be able to get a sum from all the total_weights.

Edit: Now you can use Aggregate to get the total

assets.aggregate(total=Sum('total_weight'))

{'total': 1234.5678}

Post a Comment for "Django Sum Of Multiplied Values"