Hello.
I have a parent Meta class and some child classes.
I would like to read the decimal_places attribute from DecimalField of my child instances using a function in my parent class.
I am able to read the attribute from inside my child classes, but I cant crack how to read from a function in the parent class.
Using @classmethod I get one error, not using it, I get another (see comments in the condensed example code below).
I'm presently learning Python and Django, so please feel free to educate me a bit here :)
thanks, Mikkel
from django.db import models
from django.shortcuts import render
class Vehicles(models.Model):
speed = models.DecimalField(max_digits=5, decimal_places=2)
@classmethod
def get_speed_decimal_places(self):
# @classmethod: Will raise 'DeferredAttribute' object has no attribute 'decimal_places'
# no classmethod: Will raise 'NoneType' object has no attribute 'decimal_places'
return self.speed.decimal_places
class Meta:
abstract = True
class Train(Vehicles):
speed = models.DecimalField(max_digits=5, decimal_places=2)
train_speed_decimals = speed.decimal_places
class Aeroplane(Vehicles):
speed = models.DecimalField(max_digits=5, decimal_places=1)
aeroplane_speed_decimals = speed.decimal_places
def SpeedView(request):
t = Train()
context = {}
# This works just fine
context['decimals_own'] = t.train_speed_decimals
# This raises error in get_speed_decimal_places()
context['decimals_cls'] = t.get_speed_decimal_places()
return render(request,'speed_index.html',context)