Django model inheritance and type checking

class Machine(models.Model): name= models.CharField( max_length=120) class Meta: abstract = True class Car(Machine): speed = models.IntegerField() class Computer(Machine) ram = models.IntegerField() 

My question is: how can I understand what type is the model of the machine. For instamce, I know that the incoming request is the children of the Machine model, but I also want to know that this is a submodel of Car.

+6
python django
source share
2 answers

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

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

Or, if you want to check if an_object instance of Car , you can use isinstance .

 isinstance(an_object, Car) # True 
+11
source share

isinstance will only work if you select an object that calls the Car class. if you do Machine.objects.all (), and later want to find out if there is a car, then you can use hasattr. as:

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

All Articles