TypeError: Abstract models cannot be instantiated (Django)

I have abstract models A and B and a child model C.

class A(models.Model):
    field1 = models.CharField(max_length=24)

    class Meta:
        abstract = True


class B(models.Model):
    field1 = models.CharField(max_length=24)

    class Meta:
        abstract = True

   def make_A(self):
      A(field1=self.field1).save()


class C(B):
    pass

If I try to run C.make_A() I get TypeError: Abstract models cannot be instantiated error. So I am forced to re-write make_A method on the child. Is there a way to write a method that instantiates A under abstract B?

The problem is not that B is abstract, the problem is that A is abstract. But you can make a "template method", that you then slightly alter in C with:

class B(models.Model):
    concrete_A = None
    field1 = models.CharField(max_length=24)

    class Meta:
        abstract = True

    def make_A(self):
        self.concrete_A.objects.create(field1=self.field1)


class C(B):
    concrete_A = SubA

With SubA a concrete subclass of A.

That being said, given I understand what you aim to do, you seem to just to some extent replicate what django-simple-history [readthedocs.io] is doing.

Back to Top