[Answered ]-Sum of the objects in a model

2๐Ÿ‘

โœ…

I think it should be:

def _valor_carrinho(self):
    return self.item_set.all().aggregate(Sum('total_price'))

to get all items for a specific Cart instance, I am NOT sure total_price works here, but to access the items of the cart it is item_set, hopefully it is enough to get you started!

The concept that that is using is reverse foreign key lookup, which is explained here

๐Ÿ‘คdm03514

0๐Ÿ‘

I am not sure that this does work as I think aggregate goes to the database layer and total_price has been defined as a property. I am going to denormalise and make the equivalent of total_price a field so that I can use the aggregate function.

๐Ÿ‘คhum3

0๐Ÿ‘

Try the following code, it works for me so it might work for you:

view.py

def get_cart(request):
    cart = Cart(request)
    cart.summary()
    return render_to_response('cart.html', dict(cart=Cart(request)),{'cart':cart})

cart.html

<h3> Total : {{ cart.summary }}</h3>
๐Ÿ‘คPratik

Leave a comment