views:

15

answers:

0

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.