Baterson Baterson - 6 months ago 22
Python Question

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

I have many classes with same field named

state
, which is
CharField
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'

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

class Meta:
abstract = True


Here my child class:

ChildClass(UsefullAbstractClass):
state = models.CharField(
max_length=100,
choices=STATE_CHOICES)


And I got


name 'STATE_CHOICES' is not defined


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

>>> c = ChildClass.objects.all()
>>> c[0].STATE_CHOICES
(('new', 'new'), ('actual', 'actual'), ('delete', 'delete'))


How can I solve this problem?

Answer
ChildClass(UsefullAbstractClass):
    state = models.CharField(
            max_length=100,
            choices=UsefullAbstractClass.STATE_CHOICES)

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 self.name = value. Both class and instance variables are accessible through the notation self.name.

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 http://docs.python.org/reference/compound_stmts.html#class-definitions

Comments