views:

24

answers:

2

Hi,

I've got a model Child inheriting from a (non abstract) model Parent. For a given instance parent of Parent, how can I know if it's a Child?

If it is,

parent.child

returns the child, but otherwise it returns a DoesNotExist exception.

Is a try/except the only way to check that?

Thanks

jul

# EDIT

I've just find the same question here: http://stackoverflow.com/questions/2202232/distinguishing-parent-models-children-with-django-inheritance.

And the answer is....

hasattr(parent, 'child')
A: 

You could use instanceof(parent, Child). It will return True for Child instances, False for Parent instances.

Ned Batchelder
(This won't work: the poster's question is about Django model inheritance, not Python inheritance.)
Piet Delport
@Ned: I guess this wasn't asked for. If `child` is an instance of `Child`, then it is also stored in the `Parent` table, so the question is (if i got it right), how to determine if an object retrieved from the `Parent` table is a child...
lazerscience
A: 

Is a try/except the only way to check that?

More or less.

If you only want an existence check, you can avoid the exception by saying Child.objects.filter(parent=parent).exists(), but if you want to do something with the child if it exists, it's better to just access it directly and handle the DoesNotExist.

Piet Delport