Baterson Baterson - 2 years ago 104
Python Question

Django. Why I cant pass parametr from abstract model class to child model field?

I have many classes with same field named

, which is
with choices. And all of this classes inherit from one abstract class. I decided to put choices variable to this abstract class:

class UsefullAbstractClass(models.Model):
NEW = 'new'
ACTUAL = 'actual'
DELETE = 'delete'

(NEW, 'new'),
(ACTUAL, 'actual'),
(DELETE, 'delete'))

class Meta:
abstract = True

Here my child class:

state = models.CharField(

And I got

name 'STATE_CHOICES' is not defined

Then I use shell
for check this variable exists. And all child class instanses has this variable

>>> c = ChildClass.objects.all()
(('new', 'new'), ('actual', 'actual'), ('delete', 'delete'))

How can I solve this problem?

Answer Source
    state = models.CharField(

Variables defined in the class definition are class variables; they are shared by all instances. To create instance variables, they can be set in a method with = value. Both class and instance variables are accessible through the notation

You can access it in any methods of ChildClass like self.STATE_CHOICES. That's why it worked for c[0].STATE_CHOICES

So it is only accessible with the instances (self.variable_name). If you want to access it outside the methods then you should do class.variable_name.

For more details please check the link

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download