Thursday, December 27, 2018

How can I read child model class' DecimalField attribute 'decimal_places' from inside a parent Meta class


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)


--
You received this message because you are subscribed to the Google Groups "Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email to django-users+unsubscribe@googlegroups.com.
To post to this group, send email to django-users@googlegroups.com.
Visit this group at https://groups.google.com/group/django-users.
To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/27f4b78d-86f8-4c73-b4bd-707ee677e530%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

No comments:

Post a Comment