How to override the default value for a model field from an abstract base class

I have a code that looks like this:

class BaseMessage(models.Model): is_public = models.BooleanField(default=False) # some more fields... class Meta: abstract = True class Message(BaseMessage): # some fields... 

and I would like to override the default value for the is_public field in the message model so that it is True for this model.

I looked through some relevant Django docs and poked around the model objects, but I was having trouble finding a suitable place for this. Any suggestions?

+25
python django django-models
Jun 16 '11 at 19:43
source share
1 answer

You can do it as follows:

 class BaseMessage(models.Model): is_public = models.BooleanField(default=False) # some more fields... class Meta: abstract = True class Message(BaseMessage): # some fields... Message._meta.get_field('is_public').default = True 

I did it once or twice. It works because the field in Message is a different instance than the field in BaseMessage. However, I doubt it is recommended ;-) It depends a lot on how internal django works, so there is no guarantee that it will work forever.

+29
Jun 16 2018-11-22T00:
source share



All Articles