[Fixed]-Django model inheritance and type check


I am not sure if I understand your question correctly. If you are trying to find out the type of a given instance you can use the built-in type function.

an_object = Car(name = "foo", speed = 80)
type(an_object) # <class 'project.app.models.Car'>

Or if you wish to check if an_object is an instance of Car you can use isinstance.

isinstance(an_object, Car) # True


isinstance would work only if you fetched the object calling the Car class.
if you do Machine.objects.all() and later want to know if is a car, what you can do is use hasattr. like:

o = Machine.objects.all()[0]
print(hasattr(o, 'car'))

Leave a comment