Issue
I have a model like this:
class InvoiceItem(models.Model):
book = models.ForeignKey(Book, on_delete=models.PROTECT)
invoice = models.ForeignKey(Invoice, on_delete=models.PROTECT, related_name='items')
title = models.CharField(max_length=100, null=True, blank=True)
price = models.IntegerField(null=True, blank=True)
discount = models.IntegerField(blank=True, default=0)
totalprice = models.IntegerField(null=True, blank=True)
count = models.IntegerField(null=True, blank=True)
and I want to calculate discount from book's discount table How can I do it? should I calculate it in models?
Solution
Here we can create property for override models fields like this (without override save() method)
class InvoiceItem(models.Model):
book = models.CharField(max_length=100)
invoice = models.PositiveIntegerField()
title = models.CharField(max_length=100, null=True, blank=True)
og_price = models.IntegerField(null=True, blank=True)
sell_price = models.IntegerField(null=True, blank=True)
discount = models.IntegerField(blank=True, default=0)
discounted_price = models.IntegerField(blank=True, default=0)
count = models.IntegerField(null=True, blank=True)
@property
def discounted_price(self):
return ((self.og_price*self.discount)/100)
@property
def sell_price(self):
return ((self.og_price - self.discounted_price))
with override save() method
class InvoiceItem(models.Model):
book = models.CharField(max_length=100)
invoice = models.PositiveIntegerField()
title = models.CharField(max_length=100, null=True, blank=True)
og_price = models.IntegerField(null=True, blank=True)
sell_price = models.IntegerField(null=True, blank=True)
discount = models.IntegerField(blank=True, default=0)
discounted_price = models.IntegerField(blank=True, default=0)
count = models.IntegerField(null=True, blank=True)
@property
def dis_price(self):
print((self.og_price*self.discount)/100)
return ((self.og_price*self.discount)/100)
@property
def selling_price(self):
print(self.og_price - self.dis_price)
return (self.og_price - self.dis_price)
def save(self, *args, **kwargs):
self.sell_price = self.selling_price
self.discounted_price = self.dis_price
super(InvoiceItem, self).save(*args, **kwargs)
Output
You need to fill only those fields
NOTE: here i changed two fields for data adding in database
book = models.CharField(max_length=100)
invoice = models.PositiveIntegerField()
Answered By - Mahammadhusain kadiwala
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.