I have a model which have a function to calculate the difference between two fields
Example:
Class MyModel(models.Model):
fieldA = models.FloatField()
fieldB = models.FloatField()
def delta(self):
return self.fieldA - self.fieldB
Id like to use this model in a GenericView. I can use the function delta as an extraContext but also id like to include the sum of all Delta results in the template, in this case I have to make an aggregate but again since delta is not a DB Field nor a Model Field I cant use it in an aggregate function.
How can accomplish this?
One way to do this is to create a Manager and defines a function with the raw SQL query. Create the model object attaching the new calculated field referencing to the model class with self.model
Almost a copy-paste from Django Documentation
Then we can use the manager function in the extra-context dictionary of the generic view. and do algebraic operations without hitting the database unnecessarily.
A better solution is create your own QuerySet class with a custom Manager. This allows to chain filters and return any computed value as a QuerySet attribute. Is taken almost directly from this snippet