1👍
Since amount
fully depends on the price
and the po_quantity
, you better use a property for this. Otherwise you introduce data duplication. You thus can implement this as:
class PurchaseOrder(models.Model):
part = models.ForeignKey(Part, on_delete=models.CASCADE)
po_quantity = models.PositiveIntegerField(default= 0)
supplier = models.ForeignKey(Supplier, on_delete=models.CASCADE)
product = models.ForeignKey(Product, on_delete=models.CASCADE)
created_date = models.DateField(auto_now_add=True)
@property
def amount(self):
return self.po_quantity * self.part.price
If you need to use the amount
when filtering, you can use .annotate(…)
[Django-doc] instead, and define this for example in a Manager
:
from django.db.models import F
class PurchaseOrderManager(models.Manager):
def get_queryset(self, *args, **kwargs):
return super().get_queryset(*args, **kwargs).annotate(
amount=F('po_quantity') * F('part__price')
)
class PurchaseOrder(models.Model):
part = models.ForeignKey(Part, on_delete=models.CASCADE)
po_quantity = models.PositiveIntegerField(default= 0)
supplier = models.ForeignKey(Supplier, on_delete=models.CASCADE)
product = models.ForeignKey(Product, on_delete=models.CASCADE)
created_date = models.DateField(auto_now_add=True)
objects = PurchaseOrderManager()
Source:stackexchange.com