Kit Sunde
Kit Sunde

Reputation: 37075

How can I use non-model serializer mixins with a ModelSerializer

Say I have a mixin like CaptchaSerializerMixin that has a field captcha that I don't have on the model. Currently I need to do:

class MyModel(CaptchaSerializerMixin, serializers.ModelSerializer):
    class Meta:
        model = MyModel
        fields = ['id', 'captcha']

Or it won't accept the captcha field. How can my Mixin supply itself to the fields list?

Upvotes: 0

Views: 723

Answers (2)

Yushin Washio
Yushin Washio

Reputation: 733

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']

Upvotes: 0

Linovia
Linovia

Reputation: 20976

You need to make sure CaptchaSerializerMixin inherit from Serializer. If you don't do that, fields won't be identified as serializers.Field.

Upvotes: 1

Related Questions