Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django model inheritance and type check

Tags:

python

django

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 Machine model. For instamce I know the incoming query is a children of the Machine model but I also want to know it is a Car submodel.

like image 243
Hellnar Avatar asked Aug 09 '10 07:08

Hellnar


People also ask

What is Verbose_name in Django?

verbose_name is a human-readable name for the field. If the verbose name isn't given, Django will automatically create it using the field's attribute name, converting underscores to spaces. This attribute in general changes the field name in admin interface.

What is @property Django?

The @property decorator is a built-in decorator in Python for the property() function. This function returns a special descriptor object which allows direct access to getter, setter, and deleter methods. A typical use is to define a managed attribute x : class C(object): def __init__(self): self.


2 Answers

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
like image 94
Manoj Govindan Avatar answered Oct 14 '22 22:10

Manoj Govindan


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'))
like image 37
mcniac Avatar answered Oct 14 '22 22:10

mcniac