Junior — Middle
Explain the inheritance principle of models in Django and how it is used in practice.
sobes.tech AI
Answer from AI
In Django, model inheritance allows creating new models based on existing ones, which helps avoid code duplication and organize data.
There are three main types of model inheritance:
-
Abstract Base Class:
- A base class is created with common fields and methods.
- No database table is created for this class.
- Child models inherit fields and methods.
-
Multi-table Inheritance:
- Each model has its own table in the database.
- The child model references the parent via a foreign key.
- Allows extending models while maintaining relationships.
-
Proxy Models:
- Do not create a new table.
- Allow changing the behavior of a model (e.g., methods) without altering its structure.
Example of an abstract base class:
from django.db import models
class TimestampedModel(models.Model):
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
class Meta:
abstract = True
class Article(TimestampedModel):
title = models.CharField(max_length=200)
content = models.TextField()
In practice, model inheritance helps reuse code, improve project structure, and facilitate maintenance.