class Products(models.Model):
Code = models.CharField(max_length=10,primary_key=True)
Product_description = models.CharField(max_length=200)
Val_tech = models.CharField(max_length=5)
Quantity = models.IntegerField()
UOM = models.CharField(max_length=5)
Rate = models.FloatField()
Value = models.FloatField()
def __str__(self):
return self.Product_description
class TableToRefer(models.Model):
Item = models.ForeignKey('Products.Product_description',primary_key=True,on_delete=models.CASCADE)
Qty = models.ForeignKey('Products.Quantity',null=True,default=0,on_delete=models.CASCADE)
Rate = models.ForeignKey('Products.Rate',null=True,default=0,on_delete=models.CASCADE)
price = models.FloatField(null=True,default = Rate*1.20)
I want to access the value of Rate field and use it in price field and automatically add the calculated price in it. How do I do it?
You can check in your save method if your price has been set. If not, the price will be automatically calculated
class TableToRefer(models.Model):
Item = models.ForeignKey('Products.Product_description',primary_key=True,on_delete=models.CASCADE)
Qty = models.ForeignKey('Products.Quantity',null=True,default=0,on_delete=models.CASCADE)
Rate = models.ForeignKey('Products.Rate',null=True,default=0,on_delete=models.CASCADE)
price = models.FloatField(null=True,default=None)
def save(*args, **kwargs):
if self.price is None:
self.price = self.Rate * 0.2
super().save(*args, **kwargs)
The solution from @hendrikschneider worked for me except for the small change.
class TableToRefer(models.Model):
Rate = models.FloatField(null=True,default=0)
Item = models.ForeignKey('Products.Product_description',primary_key=True,on_delete=models.CASCADE)
Qty = models.ForeignKey('Products.Quantity',null=True,default=0,on_delete=models.CASCADE)
Rate = models.ForeignKey('Products.Rate',null=True,default=0,on_delete=models.CASCADE)
price = models.FloatField(null=True,default=None
def save(self,*args, **kwargs):
if self.price is None:
self.price = self.Rate * 0.2
super().save(*args, **kwargs)
As you can see, in the save method, you need to add self as the first parameter and it will add the value as 0.2 of rate entered.
Code Execution (attaching screenshots)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.