Django does a great job of mapping your model fields to the database columns. The ORM works for most of the common cases.
One of the cases where it does not work is working with calculated fields while displaying reports. Typically, a calculated field is output of some arithmetic calculations on other fields, and so does not need a corresponding database column.
The first solution that I thought of was a property. The set method can be empty, and the get method can do the calculation and return its output. Works well.
The biggest disadvantage of using a property is that you cannot using with the Field Lookups, which is used by most of the QuerySet API. So you cannot filter or order the query set using properties. The only way to do it is bypass the ORM and write custom SQL queries.
If you think that this is too much trouble, there is another solution. You can create a model field for the calculated field and calculate its value when the model is saved. For example,
class Person(models.Model): ... def save(self): self.cost_per_unit = total_cost/no_of_units super(Person, self).save()
The big disadvantage of this solution is that you would keep redundant data in the database. This not only means wastage of space, but can also be a threat to data integrity. However, this lets you use it effectively with the QuerySet API and hence in the admin interface as well.
Both the solutions come with their pros and cons. An ideal solution would be ability to define this through something like annotate, where custom functions can be defined.
Do you know of any other way to represent calculated fields in Django?