In Django, using __init__() method of non-abstract parent model to record class name of child model

Posted by k-g-f on Stack Overflow See other posts from Stack Overflow or by k-g-f
Published on 2010-06-09T02:33:35Z Indexed on 2010/06/09 2:42 UTC
Read the original article Hit count: 124

Filed under:

In my Django project, I have a non-abstract parent model defined as follows:

class Parent(models.Model):
    classType = models.CharField(editable=False,max_length=50)

and, say, two children models defined as follows:

class ChildA(Parent):
    parent = models.OneToOneField(Parent,parent_link=True)

class ChildB(Parent):
    parent = models.OneToOneField(Parent,parent_link=True)

Each time I create an instance of ChildA or of ChildB, I'd like the classType attribute to be set to the strings "ChildA" or "ChildB" respectively. What I have done is added an _ _ init_ _() method to Parent as follows:

class Parent(models.Model):
    classType = models.CharField(editable=False,max_length=50)

    def __init__(self,*args,**kwargs):
        super(Parent,self).__init__(*args,**kwargs)
        self.classType = self.__class__.__name__

Is there a better way to implement and achieve my desired result? One downside of this implementation is that when I have an instance of the Parent, say "parent", and I want to get the type of the child object linked with "parent", calling "parent.classType" gives me "Parent". In order to get the appropriate "ChildA" or "ChildB" value, I need to write a "_getClassType()" method to wrap a custom sql query.

© Stack Overflow or respective owner

Related posts about django-models