As was found out with the conversation with Mike Dewhirst, the error appears to
be because of wrong understanding of operator precedence
<https://docs.python.org/3/reference/expressions.html#operator-precedence>.
That's easy to correct with parentheses.
Except for that, I wouldn't do it that way; I wouldn't store the total price in
the database, because it's likely to create problems. Models that have not (yet)
been saved to the database will not have a total price. Models that have been
loaded from the database, modified, but not (yet) updated in the database will
have a wrong total price. Saving to the database with bulk operations or with
plain SQL may result in no total price. These are all symptoms of storing
redundant information in the database, which is something that should be avoided.
Instead, I would do this:
class Stock(models.Model):
unit_price = models.DecimalField(max_digits=10, decimal_places=2,
default='0', blank=True, null=True)
quantity = models.IntegerField(default='0', blank=True, null=True)
reorder_level = models.IntegerField(default='0', blank=True, null=True)
@property
def total_price(self):
return (self.quantity + self.reorder_level) * self.unit_price
On 10/04/2022 20.49, tech george wrote:
Hello,
I am trying to calculate fields directly from a model but no luck. I want to
get total_price from quantity, reoder_level and unit price. My code is abelow,
Please advise.
class Stock(models.Model):
unit_price = models.DecimalField(max_digits=10, decimal_places=2,
default='0', blank=True, null=True)
quantity = models.IntegerField(default='0', blank=True, null=True)
total_price = models.DecimalField(max_digits=10, decimal_places=2,default=1)
reorder_level = models.IntegerField(default='0', blank=True, null=True)
def save(self, *args, **kwargs):
self.total_price = self.quantity + self.reorder_level * self.unit_price
super(Stock, self).save(*args, **kwargs)
What am i my doing wrong
Regards,
--
You received this message because you are subscribed to the Google Groups
"Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an
email to django-users+unsubscr...@googlegroups.com.
To view this discussion on the web visit
https://groups.google.com/d/msgid/django-users/CADYG20HBcMMGq6QodO0v%2BeZVmfS%2Bmr4aCSro5FZeeRLFdQztnQ%40mail.gmail.com
<https://groups.google.com/d/msgid/django-users/CADYG20HBcMMGq6QodO0v%2BeZVmfS%2Bmr4aCSro5FZeeRLFdQztnQ%40mail.gmail.com?utm_medium=email&utm_source=footer>.
--
You received this message because you are subscribed to the Google Groups "Django
users" group.
To unsubscribe from this group and stop receiving emails from it, send an email
to django-users+unsubscr...@googlegroups.com.
To view this discussion on the web visit
https://groups.google.com/d/msgid/django-users/8efea23c-52d8-6ac1-b94e-3cb9ad46d086%40antonischristofides.com.