Thursday, December 27, 2018

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

Ah! It turns out that there is a _meta method for that.

class Vehicles(models.Model):
   
   
def get_speed_decimal_places(self):
       
return self._meta.get_field('speed').decimal_places


Though I'm still wondering why my first shot at the problem worked from within the child class, but not from the parent class.


Mikkel

torsdag den 27. december 2018 kl. 20.59.43 UTC+1 skrev Mikkel Kromann:

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/6123eb77-5c35-49e9-961d-860e06b9d7cb%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

No comments:

Post a Comment