[Fixed]-Regarding Base and Child Models: Django

1👍

Assuming you are using Django 1.7 or above, you should be able to use the system check framework; specifically, the field, model and manager checks.

I believe it would look something like this:

from django.core import checks
from django.db import models


class Base(models.Model):

    class Meta:
        abstract = True

    @classmethod
    def check(self, **kwargs):
        errors = super(Base, self).check(**kwargs)
        if not self._meta.abstract and not hasattr(self, 'sub_field_a'):
            errors.extend([
                checks.Error(
                    'missing sub_field_a',
                    hint='Add a field named sub_field_a',
                    obj=self,
                    id='myapp.E001',
                )
            ])
        return errors

0👍

Isn’t the whole point of inheritance is to reduce and reuse common code. In this case we know sub_field_a always need to be defined. In that case why not add it to the base model like this:

class Base(models.Model):
    sub_field_a = models.CharField(max_length=255)
    class Meta:
        abstract = True

class SubA(Base):
    sub_field_c = models.CharField(max_length=255)

class SubB(Base):
    sub_field_b = models.CharField(max_length=255)
    sub_field_c = models.CharField(max_length=255)

This totally invalidates the use case that is required here. Hope this helps 🙂

Leave a comment