[Fixed]-Django model inheritance and type check

29๐Ÿ‘

โœ…

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)
an_object.save()
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
๐Ÿ‘คManoj Govindan

12๐Ÿ‘

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'))
๐Ÿ‘คmcniac

Leave a comment