I have a model called Actual:
# Actual parts table
class Actual(models.Model):
vendor = models.ForeignKey(Vendor, on_delete=models.CASCADE, verbose_name="Vendor name", related_name="actualvendor")
number = models.CharField("External part number", max_length=32, unique=True, blank=True, null=True)
description = models.CharField(max_length=64, blank=True)
pq = models.DecimalField(max_digits=7, decimal_places=2, default=1)
mrrp = models.DecimalField(max_digits=10, decimal_places=2)
# Model metadata
class Meta:
unique_together = ["vendor", "number"]
verbose_name_plural = "actual external parts"
# Display below in admin
def __str__(self):
return f"{self.number}"
I also have another model called Offer:
class Offer(models.Model):
sync_id = models.ForeignKey(Sync, on_delete=models.CASCADE, verbose_name="Internal part number", related_name="part")
discount = models.DecimalField(max_digits=3, decimal_places=2, default=0)
moq = models.DecimalField(max_digits=4, decimal_places=2, default=1)
status = models.CharField(max_length=20, choices=OFFERSTATUS_CHOICES, default=1)
actual = models.OneToOneField(Actual, on_delete=models.CASCADE)
# Display something in admin
def __str__(self):
return f"Offer {self.id} for {self.sync_id}"
# Calculate the price
def price(self):
return self.actual.mrrp * (1-self.discount)
I am trying to calculate the 'price' in the 'Offer' model using 'mrrp' but 'mrrp' is from the 'Actual' model.
I am able to do so with the code I've attached but as you can see in the django admin, the 'actual' shows up as a field. I don't want it to appear as a field. I just want 'actual' to be a variable that is equal to the value of 'mrrp'. That way I can use it to calculate the price.
Is there another way to reference fields from another model? Surely fields aren't the only way?
I solved this with a property decorator. I had the right idea but did not place a property decorator on top of the function that calculates the price. Use a property decorator to display the data as you would a field in Django.
I added the below to the bottom of my model:
@property
def price(self):
return self.actual.mrrp * (1-self.discount)