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?

+3


source to share


3 answers


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.



+7


source


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.

+1


source


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"

      

+1


source







All Articles