Junior — Middle
Can you explain what is meant by an abstract model in Django and how it is used?
sobes.tech AI
Answer from AI
In Django, an abstract model is a base class of a model that does not create a separate table in the database but allows inheriting common fields and methods in child models. This is convenient for code reuse and organizing models.
To create an abstract model, you specify abstract = True inside its Meta 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=100)
content = models.TextField()
In this example, TimestampedModel does not create a table, but the fields created_at and updated_at will be inherited by the Article model. This helps avoid code duplication when working with common fields.