June
June

Reputation: 2217

How to extend django abstract base model by inheritance?

I'm trying to extend my django abstract base model via inheritance, but django model's behavior that automatically sets abstract = True to abstract = False on any subclasses of abstract models is bothering me.

So the situation is

from django.db.models import Model
from django.db.models.base import ModelBase

Class TimeStampedModel(Model):
    created_time = DateTimeField()
    modified_time = DateTimeField()

    class Meta:
        abstract = True
        ordering = ('created_time',)
        get_latest_by = 'created_time'


class RecordModelMetaClass(ModelBase):
    # NOT IMPLEMENTED YET
    pass


class RecordModel(TimeStampedModel):
    __metaclass__ = RecordModelMetaClass

    recording_model = NotImplemented
    recording_fields = NotImplemented

Where the abstract TimeStampedModel is base model for abstract RecordModel.

The problem is that Django's metaclass ModelBase automatically converts RecordModel's abstract = True to abstract = False when RecordModel is defined in import time.

Is there any way to turn off this django's behavior?

Upvotes: 3

Views: 1997

Answers (1)

Daniel Roseman
Daniel Roseman

Reputation: 599620

Yes, and this is documented:

If the child wants to extend the parent’s Meta class, it can subclass it.

In your case:

class RecordModel(TimeStampedModel):
    class Meta(TimestampedModel.Meta):
        abstract = True

Upvotes: 4

Related Questions