When writing a mixin that applies on a ModelSerializer
(Linovia’s approach should work on plain serializers), you need to use the SerializerMetaClass
like this:
class CaptchaSerializerMixin(metaclass=serializers.SerializerMetaClass):
captcha = SomeField()
You do still need to mention "captcha" in your Meta.fields
.
Similar more detailed answer: https://stackoverflow.com/a/58304791/2547556
The above is the recommended way, but if you really can’t mention it in your Meta.fields
, then a hacky way would be:
class MyModel(CaptchaSerializerMixin, serializers.ModelSerializer):
def get_fields(self):
fields = super().get_fields()
fields.update(CaptchaSerializerMixin.get_fields(self))
return fields
class Meta:
model = MyModel
fields = ['id']