How to change default value for a field of a parent Model class ?
class WebPage(models.Model):
name = models.CharField(max_length=50, unique=True)
title = models.CharField(max_length=150, default="value1")
class CustomWebPage(WebPage)
author = models.CharField(max_length=30, default="author1")
keywords = models.CharField(max_length=300, default="word1, word2")
# here I would like to set/change parent's "title" field default value to something else
Thanks !
You should be able to redefine the field name with the new default value.
title = models.CharField(max_length=150, default="something else")
Logically, it’s the same thing as overriding any function or other class attribute.
Thanks for your answer. I thought maybe there is another option because I like the definition which is in parent class
and default
is really the only thing I would like to change.
There is, but it ends up being more work, more lines of code, and therefore less straight-forward and understandable.
A field in a model is not just a variable - it’s an object itself with its own attributes and behavior. The model classes are constructed using a fair bit of metaprogramming in the model class. You change that behavior at your own risk (and there are many).
I see no benefits in taking an alternate approach.