I'm using Python 3.6 with Django 1.11.9 and rest_framework 3.6.2.
I want to inherit from serializers.Serializer to make a SharingSerializer class, that I want to be abstract, because I want to inherit from the latter to implement some ArticleSharingSerializer, ImageSharingSerializer,... and so on.
What I've tried so far:
from abc import ABCMeta, abstractmethod
from rest_framework import serializers
...
class SharingSerializer(serializers.Serializer, metaclass=ABCMeta):
course = serializers.PrimaryKeyRelatedField(queryset=Course.objects.all())
students = serializers.PrimaryKeyRelatedField(queryset=User.objects.all(), many=True)
@abstractmethod
def validate(self, data):
# Doing validation stuff with "course" and "students" fields
...
return data
class ArticleSharingSerializer(SharingSerializer):
articles = serializers.PrimaryKeyRelatedField(queryset=Article.objects.all(), many=True)
def validate(self, data):
data = super().validate(data)
# Doing validation stuff with "articles" and self.context["request"].user
...
return data
But when trying to "runserver", I get the following error:
File ".../school/serializers.py", line 11, in <module>
class SharingSerializer(serializers.Serializer, metaclass=ABCMeta):
TypeError: metaclass conflict: the metaclass of a derived class must be a (non-strict) subclass of the metaclasses of all its bases
Do you know how I can successfully achieve what I'm trying to achieve?
UPDATE : I want to take advantage of the @abstractmethod "enforcement" on instantiation that ABC provides.
UPDATE 2 : TLDR : The best answer given by Ahmed Hosny (see below) is this link