I want to access the inherited fields of a model from within that models init function -
class Parent(models.Model):
parent_field = models.TextField(default="parent text")
class Meta:
abstract = True
class Child(Parent):
def __init__(self, *args, **kwargs):
super(Child, self).__init__(*args, **kwargs)
self.parent_field.default="child text"
However when I try and initialize a Child object, self.parent_field
(in the code above), is already a unicode object rather than a field object.
I know I'm not supposed to be overriding fields. I guess I'd need to override something in the meta class. Is there a way of doing this? Or am I just making trouble?
The __init__ method is the Python equivalent of the C++ constructor in an object-oriented approach. The __init__ function is called every time an object is created from a class. The __init__ method lets the class initialize the object's attributes and serves no other purpose. It is only used within classes.
The __str__ method just tells Django what to print when it needs to print out an instance of the any model.
Do Django models support multiple-column primary keys? ¶ No. Only single-column primary keys are supported.
verbose_name is a human-readable name for the field. If the verbose name isn't given, Django will automatically create it using the field's attribute name, converting underscores to spaces. This attribute in general changes the field name in admin interface.
You are confusing model data with model metadata.
Fields belong to the metadata. They are used at loading & saving data.
The model's properties, on the contrary, are always data. That's why self.parent_field
is a unicode object.
To access the field objects, you need to access the model's metadata, namely self._meta
object (that's where all the stuff from the class Meta
also goes). The fields are in self._meta.fields
, which is a list of django.models.Field
objects defined for the class.
use _meta.get_field
as below:
class Child(Parent)
def __init__(self, *args, **kwargs):
super(Child, self).__init__(*args, **kwargs)
self._meta.get_field('parent_field').default="child text"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With