Search code examples
pythondjangodjango-modelsmetaclassabstract-methods

How to declare abstract class and methods for model implementation?


I wonder if there is a way in Django to create an abstract class where I can declare a method that should be implemented in a model.

Normally, in Python, we declare abstract class like this:

import abc

class MyABC(metaclass=abc.ABCMeta):

    @abc.abstractmethod
    def do_something(self, value):
        raise NotImplementedError

And then implement it like this:

class MyClass(MyABC):

    def do_something(self, value):
        pass

What I did with django is:

import abc
from django.db import models

class MyClass(metaclass=abc.ABCMeta):

    @abc.abstractmethod
    def __str__(self):
        raise NotImplementedError

class MyClass2(models.Model, MyClass):

    def __str__(self):
        pass

But this gives me error:

TypeError: metaclass conflict: the metaclass of a derived class must be a (non-strict) subclass of the metaclasses of all its bases

I don't understand what I did wrong here. MyClass2 should inherit from MyClass and from models.Model.

What I did wrong? Why this is wrong? What is the better way of declaring methods that should be implemented in models?


Solution

  • For django model you can try this.

    from django.db import models

    class MyClass(models.Model):
    
       class Meta:
          abstract = True
       def __str__(self):
          raise NotImplementedError
    
    class MyClass2(MyClass):
    
       def __str__(self):
           pass
    

    refer this hope this helps.