[Answered ]-Struggling with aggregate and subtraction in Django and PostgreSQL

1👍

Given I understand what you try to do, you can just work with:

class Inventory(models.Model):
    # …

    def __str__(self):
        return f'{self.product}\n{self.description}\n{self.paid}{self.bin}\n{self.listdate}\n{self.listprice}\n{self.solddate}\n{self.soldprice}\n{self.shipdate}\n{self.shipcost}'

    @property
    def profit(self):
        return self.soldprice - self.paidfor - self.shipcost

Since the fields can be NULLable (making it more complicated), you might have to work with default values:

class Inventory(models.Model):
    # …

    @property
    def profit(self):
        return (self.soldprice or 0.00) - (self.paidfor or 0.00) - (self.shipcost or 0.00)

But using 0.00 as "fallback value" is a bit strange if it is NULL: NULL usually means "unknown", not zero. So in that case if one of the fields is None, we return None:

class Inventory(models.Model):
    # …

    @property
    def profit(self):
        if self.soldprice is not None and self.paidfor is not None and self.shipcost is not None:
            return self.soldprice - self.paidfor - self.shipcost

Leave a comment