django accessing subclasses of models django accessing subclasses of models django django

django accessing subclasses of models


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'):        ...


You can't do that. Person model queries a different table - appname_person, Butcher, a different one and Driver another.

The inheritance in Django models only saves you the writing of the fields again and doesn't query multiple tables - It shouldn't either.

To achieve something to this effect you should have a Person.type in the db, or you should use Generic Relations, where you make Person to have generic relations with all of the subtypes you intend to create (without actually inheriting, and defining generic foreignkey.)

If the fields in each of those models are same, just add a type field to the person; or if the fields are quite different, follow the generic relations approach.