Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Model Inheritance and Property Default Value

I have a main class with a category property and several subclasses. I'd like to set the default category for each subclass. For example:

class BaseAd(models.Model):
    CATEGORY_CHOICES = ((1, 'Zeta'), (2, 'Sigma'), (3, 'Omega'),)
    category = models.IntegerField(choices=CATEGORY_CHOICES)
    ...

class SigmaAd(BaseAd):
    additional_prop = models.URLField()
    category = models.IntegerField(default=2, editable=False)

Of course, my example is not functional due to a FieldError. How does one go about "overriding" the property value? Or is it a function of the admin I should be focusing on?

like image 902
John Giotta Avatar asked May 04 '10 17:05

John Giotta


1 Answers

You'll have to override it in the __init__() method of the child. Check the keyword arguments passed to see if category has been given a value, and if not set it to 2 before passing it to the parent.

like image 191
Ignacio Vazquez-Abrams Avatar answered Sep 21 '22 23:09

Ignacio Vazquez-Abrams