views:

51

answers:

2

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?

+2  A: 

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.

Ignacio Vazquez-Abrams
Do you have a simple example?
John Giotta
`if 'category' not in kwargs:` ` kwargs['category'] = 2` `super(...).__init__(**kwargs)` http://docs.djangoproject.com/en/dev/ref/models/instances/#django.db.models.Model
Ignacio Vazquez-Abrams
Surely that should be `kwargs.setdefault('category', 2)`
Daniel Roseman
A: 

I figured this one out:

class SigmaAdMan(admin.ModelAdmin):
exclude = ('category',)

def save_model(self, request, obj, form, change):
    obj.category = 2
    obj.save()

Not sure if its the best approach, but its functional

John Giotta
I just wanted to note why I took Ignacio's solution over mine. His approach easily dealt with the property without ModelAdmin intervention. It was ideal when dealing with data not entered via the Django admin interface.
John Giotta