updating DecimalField with value received from other model

Hi all,

I have the following models:

  class Sale(models.Model):
     location= models.CharField(max_length=300)
     price = models.DecimalField(decimal_places=2, max_digits=12)
  class Product(models.Model):
     product = models.CharField(max_length=300)
     price = models.DecimalField(decimal_places=2, max_digits=12)

that I’m trying to update with:

      discounted_price = Product.objects.filter(product=product).first() 
      completed_sale= Sale.objects.filter(id=id).first()
      best_price =  getattr(discounted_price, "price") 
      completed_sale.price =best_price 
      completed_sale.save(update_fields=["price "]) 

Basically I’m retrieving the price from a product and updating the sale price, both models have a price field of type DecimalField(decimal_places=2, max_digits=12) but I can’t manage to update the sale price with completed_sale.price =best_price

IT should be pretty straightforward but the field is not updated. I have also some other text fields in the 2 models that are updated without any issues following this structure.

Do I have to somehow cast the DecimalField or am I missing something?

Thanks in advance

Side note: When posting blocks of code here, surround the code between lines of three backtick - ` characters. This means you’ll have a line of ```, then your code, then another line of ```. This forces the forum software to keep your code properly formatted. Also, for snippets on a single line, you can enclose the snippet between single backtick characters. (I’ve taken the liberty of editing your original post.)

Couple items.

  • Instead of:

you can use:
best_price = discounted_price.price

  • You have a space in the update_fields parameter:

I am not sure that that is the cause of the issue, but it’s still worth fixing.

  • In both cases where you’re using the expression .filter(...).first(), you’re a lot better off using .get(...), especially when there should only be one instance retrieved. (You should be handling a null response either way, so it’s not like this is saving you any code.)

Beyond these items, if you are getting an error, please post the full error and traceback here. (also enclosed between lines of three backtick characters)

Thanks a lot! I switched to

Sales.objects.filter(id=id).update(sales_status="sold", etc... )

and it works!