Search code examples
inheritancedjango-modelsdefault-value

How do you change field arguments in Django model subclasses?


Let's say I have some Django model that is an abstract base class:

class Foo(models.Model):
    value=models.IntegerField()

    class Meta:
        abstract = True

and it has two derived classes, where I'd like the default value of the field to be different for each child classes. I can't simply override the field

class Bar(Foo):
    value=models.IntegerField(default=9)

because Django won't let you override fields in subclasses. I've seen posts about trying to changes available choices, but in this case I care mostly about changing the default value. Any advice?


Solution

  • The problem with redefining the save method as suggested in the other answer is that your value will not be set until you save your model object. Another option that doesn't have this problem is to redefine the __init__ in the child class (Bar class):

    def __init__(self, *args, **kwargs):
        if 'value' not in kwargs:
            kwargs['value'] = 9
        super(Bar, self).__init__(*args, **kwargs)