Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Access parent fields in a django model's init method

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?

like image 207
Aidan Ewen Avatar asked Feb 16 '13 10:02

Aidan Ewen


People also ask

What is __ init __ method do in models?

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.

What is __ str __ In Django model?

The __str__ method just tells Django what to print when it needs to print out an instance of the any model.

Can Django model have two primary keys?

Do Django models support multiple-column primary keys? ¶ No. Only single-column primary keys are supported.

What is Verbose_name in Django?

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.


2 Answers

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.

like image 192
mderk Avatar answered Sep 24 '22 22:09

mderk


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"
like image 32
dalang Avatar answered Sep 26 '22 22:09

dalang