2

I have a few Serializers that share a few fields like meta_id, category_id and so on.

Obviously I could just declare these on the serializer as a SerializerMethodField individually but I would like to find a way to reuse the logic, either with a Mixin, Decorator, or inheritance.

How can I declare a base serializer and inherit it— while still inheriting from serializers.ModelSerializer? So that I can reuse the get_meta_id and make sure it shows up in the fields?

class Foo(serializers.ModelSerializer, somethingHere?):
    meta_id = Serializers.SerializerMethodField()

class Meta:
    model = Foo
    fields = [...]

    def get_meta_id(self, obj):
        ...

Is it possible to just pass two parameters into the class

4
  • Is your meta_id field a read_only field? or both read and write field? Commented Feb 23, 2020 at 5:26
  • @ArakkalAbu it's a read only field– it's coming from another model Commented Feb 23, 2020 at 6:15
  • That's not I meant. whether the common fields are used only in Serialization purpose? Commented Feb 23, 2020 at 8:05
  • Yeah, they are only used for serialization. Commented Feb 23, 2020 at 8:38

2 Answers 2

1

You can crete a Base serializer and use inheritence for other serializers.Like that:

class BaseSerializer(serializers.Serializer):
#your codes and extra fields
    test_field = serializer.SerializerMethodField()

    def get_test_field(self.obj):
        return 'test' # or you can use obj instance here

class ExtendedSerializer(BaseSerializer,serializers.ModelSerializer):
#your extra fields

    class Meta:
        fields = BaseSerializer.Meta.fields + () # you can add your additional fields here
Sign up to request clarification or add additional context in comments.

2 Comments

but in this case the model is defined in the metaclass of baseserializer already. I need this to work for many models
Ok, I updated my answer, you can define BaseSerializer as serializers.Serializer. But with this way, you must add serializers.ModelSerializer to your child serializers.
0
class BaseSerializer(serializers.ModelSerializer): # The BaseSerializer class inherit everthing from ModelSerializer
    class Meta(serializers.ModelSerializer.Meta): # The BaseSerializer.Meta inherits everything from ModelSerializer.Meta
        def get_meta_id(self, obj):
            return self.meta_id


class Foo(BaseSerializer):
    meta_id = Serializers.SerializerMethodField()

    class Meta(BaseSerializer.Meta): # Here you should get the ModelSerializer.Meta + your custom get_meta_id
        model = Foo
        fields = [...]

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.