I'm using subclasses in my django-models like this:
class Person(models.Model):
name = models.CharField(max_length=100)
...
class Butcher(Person):
...
class Driver(Person):
...
In my view i want to do certain things depending on the subclass of the Person-class, like this:
def person_detail_view(request, slug):
person = Person.objects.get(slug=slug)
if person.butcher:
...
elif person.driver:
...
But this gives me a DoesNotExist-Error when the Person is a Driver. Is there a way to ask the Person class for its subclass?
Thanks in advance Jacques
Your basic logic is sound; the problem is in how you're testing. You have to check for the presence of the attribute, not it's value. For example:
def person_detail_view(request, slug):
person = Person.objects.get(slug=slug)
if hasattr(person, 'butcher'):
...
elif hasattr(person, 'driver'):
...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With