Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

django accessing subclasses of models

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

like image 854
jacques Avatar asked May 02 '11 09:05

jacques


1 Answers

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'):
        ...
like image 171
Chris Pratt Avatar answered Sep 30 '22 18:09

Chris Pratt