Sobes.tech
Junior — Middle

Can you explain the concept of an abstract model in Django and how it is used in development?

sobes.tech AI

Answer from AI

In Django, an abstract model is a base class for models 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 when multiple models share common attributes.

Example of an abstract model:

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()

class Comment(TimestampedModel):
    article = models.ForeignKey(Article, on_delete=models.CASCADE)
    text = models.TextField()

Here, TimestampedModel contains fields for storing creation and update times. It does not create a table, but Article and Comment inherit these fields, simplifying maintenance and extension of the code.