Accessing parent fields in init method of django model
I want to access the inherited fields of the model from within this 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 to initialize the Child object, self.parent_field
(in the above code), it is already a unicode object, not a field object.
I know that I shouldn't override fields . I think I need to override something in the meta class. Is there a way to do this? Or am I just making trouble?
source to share
You are mixing model data with model metadata. Fields are metadata. They are used when loading and saving data. In contrast, model properties are always data. Therefore it self.parent_field
is a unicode object. To access the field objects, you need to access the metadata of the model, namely the object self._meta
(which also contains all the stuff from class Meta
). The fields are in self._meta.fields
, which is a list of objects django.models.Field
defined for the class.
source to share
OK my test and working code -
class Parent(models.Model):
parent_field = models.TextField(default="parent default")
class Meta:
abstract = True
class Child(Parent):
def __init__(self, *args, **kwargs):
for f in self._meta.fields:
if f.attname == "parent_field":
f.default = "child default"
super(Child, self).__init__(*args, **kwargs)
Thanks to mderk.
source to share