Skip to content Skip to sidebar Skip to footer

How To Inherit Objects In Django?

is there a link or tutorial on how to inherit an objects in django? let us say that i have a vehicle as a parent and a car and a truck for it's child. if it is possible, is it done

Solution 1:

Exactly the same as python inheritence

class Vehicle(Model):
    name = models.TextField()

class Car(Vehicle):
    passengers = PositiveIntegerField()

class Truck(Vehicle):
    tonnage = FloatField()

>>> Car.objects.create(name='Beetle', passengers = 5)
<Car: name="Beetle",passengers=5>
>>> Truck.objects.create(name='Mack', tonnage=4.5)
<Truck: name="Mack,tonnage=4.5>
>>> Vehicle.objects.all()
[<Vehicle: name="Beetle">,<Vehicle: name="Mack>]
>>> v = Vehicle.objects.get(name='Beetle')
>>> (bool(v.car), bool(v.truck))
(True, False)
>>> v.car
<Car: name="Beetle",passengers=5>
>>> v.truck
None

https://docs.djangoproject.com/en/dev/topics/db/models/#model-inheritance


Solution 2:

It's worth noting that while Django supports a couple of inheriting methods, none of them behave in a polymorphic manner, that is, your can't make a query on a Vehicle model and get a Car instance if you use an abstract base class, and if you use Multi table inheritance, you can't use the behavior of the subclass from a base class model instance.

There are some apps and snippets trying to address this, but I don't find them very friendly to integrate.


Solution 3:

Since Django uses Python, normal Python inheritance works. For more information about inheriting models, see the Django documentation about models, especially the section about Model inheritance.


Post a Comment for "How To Inherit Objects In Django?"