Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to override the default value of a Model Field from an Abstract Base Class

I've got some 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'd like to override the default value of the is_public field in the Message model so that it's True for that model.

I've looked through some relevant Django docs and poked around the model objects but I'm having trouble finding the right place to do this. Any suggestions?

like image 893
John Debs Avatar asked Jun 16 '11 19:06

John Debs


1 Answers

You can actually do this 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 have done this once or twice. It works, because the field on Message is a different instance than the field on BaseMessage. However, I doubt it's recommended ;-) It depends a lot on how django internals currently work, so there's no guarantee that it will work forever.

like image 175
melinath Avatar answered Oct 10 '22 22:10

melinath