开发者

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.I开发者_如何学CntegerField(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?


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.


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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜