view raw
Pierangelo Orizio Pierangelo Orizio - 8 months ago 39
Python Question

Cannot convert {'price_total__sum': Decimal('258.00')} to Decimal

I get this error when I do a Sum of an entire column:

Cannot convert {'price_total__sum': Decimal('258.00')} to Decimal

here the entire project:

def add_to_order(request):
if request.method == "POST":
form = AddOrderForm(request.POST)
if form.is_valid():
post =
post.user = request.user
post.published_date =
post.tot_price = CartItem.objects.filter('price_total'))
cart_list = CartItem.objects.filter(
for cart in cart_list:
formOrder = AddOrderItemForm(request.POST)
post_cart =
post_cart.order = post
post_cart.product = cart.product
post_cart.composition = cart.composition
post_cart.price = cart.price
post_cart.quantity = cart.quantity = cart.price_total
post_cart.price_discount = cart.price_discount
post_cart.price_reserved = cart.price_reserved
#cart_list.delete() #cancello carrello dopo ordine
return redirect('/order',
form = AddOrderForm()
return render(request, 'order-form.html', {'form': form})

My Models Order, that receive the sum value, and the form:

class Order(models.Model):
user = models.ForeignKey(User, null=True, blank=True, verbose_name="Utente")
code = models.CharField('Codice', max_length=250, null=True, blank=True)
tot_price = models.DecimalField('Prezzo', max_digits=10, decimal_places=2, blank=True, null=True)
tot_discount = models.DecimalField('Totale Scontato', max_digits=10, decimal_places=2, blank=True, null=True)
tot_price_reserved = models.DecimalField('Prezzo Scontato Riservato', max_digits=10, decimal_places=2, blank=True, null=True)
pub_date = models.DateTimeField('date published', editable=False)
inlavorazione = models.BooleanField('in lavorazione', default=False)
pagato = models.BooleanField('pagato', default=False)
spedito = models.BooleanField('spedito', default=False)
chiuso = models.BooleanField('chiuso', default=False)

def save(self, *args, **kwargs):
self.pub_date =
super(Order, self).save(*args, **kwargs) # Call the "real" save() method.

def __unicode__(self):
return self.pub_date.strftime('%Y-%m-%d')

class Meta:
verbose_name_plural = "Ordine"
ordering = ['id']


class AddOrderForm(ModelForm):
class Meta:
model = Order
fields = ['user', 'tot_price', 'tot_discount', 'tot_price_reserved']


As the error shows, your aggregate() call returns a dictionary: {'price_total__sum': Decimal('258.00')}. You can't set that dict as a DecimalField in the target model; you need to extract the actual value first.

price_total = CartItem.objects.filter('price_total'))
post.tot_price = price_total['price_total__sum']