I am trying to wrap my head around how proxy model works. Supposed I have a base class called Animal, and I would like to implement two sub-classes: Dog and Cow. They have the same data requirements, so I don't really want to create two separate tables. So I am trying using proxy models:
class Animal(models.Model):
name = models.CharField()
animal_type = models.CharField(choices=(('Dog','Dog'),('Cow','Cow')))
def get_sound(self):
if animal_type == 'Dog':
return self.dog.get_sound() #doesn't work
elif self.animal_type == 'Cow':
return self.cow.get_sound() #doesn't work
class Dog(Animal):
class Meta:
proxy=True
def get_sound(self):
return 'Woof'
class Cow(Animal):
class Meta:
proxy=True
def get_sound(self):
return 'Moo'
The problem I have is, how can I access the sub-class methods from the parent class? I have it as self.dog.get_sound()
. This is possible in multi-table inheritance, but does not work in a proxy model.
>>obj = Animal.objects.create(name='Max', animal_type='Dog')
>>obj.get_sound()
'Woof' <-- what I'd like it to return
Is proxy model the wrong way to do this? Would prefer to keep one table.