gadss
gadss

Reputation: 22489

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 in the models.py? and how is it work?

thanks...

Upvotes: 0

Views: 315

Answers (3)

Thomas
Thomas

Reputation: 11888

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

Upvotes: 4

Facundo Olano
Facundo Olano

Reputation: 2609

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.

Upvotes: 1

Some programmer dude
Some programmer dude

Reputation: 409166

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.

Upvotes: 0

Related Questions