My application uses class inheritance to minimize repetition across my models. My models.py looks kind of like this:
class BaseModel(models.Model):
title = models.CharField(max_length=100)
pub_date = models.DateField()
class Child(BaseModel):
foo = models.CharField(max_length=20)
class SecondChild(BaseModel):
bar = models.CharField(max_length=20)
Now most of the time, my views and templates only deal with instances of Child or SecondChild. Once in a while, however, I have a situation where I have an instance of BaseModel, and need to figure out which class is inheriting from that instance.
Given an instance of BaseModel, let's call it base, Django's ORM offers base.child and base.secondchild. Currently, I have a method that loops through all of them to figure it out. It would look something like this:
class BaseModel(models.Model):
...
def get_absolute_url(self):
url = None
try:
self.child
url = self.child.get_absolute_url()
except Child.DoesNotExist:
pass
if not url:
try:
self.secondchild
url = self.secondchild.get_absolute_url()
except SecondChild.DoesNotExist:
pass
if not url:
url = '/base/%i' % self.id
return url
That is hopelessly ugly, and gets uglier with every additional child class I have. Does anybody have any ideas on a better, more pythonic way to go about this?