Model inheritance and default property value

I have a main class with a category property and several subclasses. I would like to set a default category for each subclass. For instance:

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 does not work due to FieldError. How can I override a property value? Or is it an admin feature that I should focus on?

+4
source share
2 answers

You will have to override it in the __init__() method for the child. Check the passed keyword arguments to see if category was set and if it is not set to 2 before passing it to the parent element.

+5
source

I get it:

 class SigmaAdMan(admin.ModelAdmin): exclude = ('category',) def save_model(self, request, obj, form, change): obj.category = 2 obj.save() 

Not sure its best approach, but its functional

0
source

Source: https://habr.com/ru/post/1308802/


All Articles