Edited with own answer: original question below.
In here it recommends a few approaches, and the simplest one to me is to just add an extra field but override save to update it, then I get standard functionality for free. So my app is now:
#views.py
highest_p2w = Car.objects.filter().order_by('-p2w')[0]
lowest_p2w = Car.objects.filter().order_by('p2w')[0]
.
#models.py
p2w = models.FloatField("Power to weight ratio",editable=False)
def save(self, *args, **kwargs):
self.p2w = (float(self.bhp) * 1000 ) / float(self.weight)
super(Car, self).save(*args, **kwargs)
The only disadvantage is that I had to do a save() on any existing records to update the value. But any new records enter the value at save() time.
Original Question
I'd like to have a dynamic value which is calculated from 2 fields returned in Django from the model.
I think I can do this with a method, but I need to be able to sort on it just like the other fields.
#Models.py:
class Car(models.Model):
weight = models.IntegerField("Weight in KG")
bhp = models.IntegerField("BHP")
I'd like to have a field called power_to_weight_ratio that just calculates ( self.bhp * 1000 ) / self.weight
As this is a dynamic value, it doesn't need to be stored. BUT it does need to be sortable, as I sorted on all the other fields in the model.
I'd think I could just do something like
power_to_weight = ( self.bhp * 1000 ) / self.weight
but I assume I need to start overriding methods to give me the ability to sort. Django docs don't seem to mention this in the model custom field documentation.
Thanks.