1
votes

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

2
Is your meta_id field a read_only field? or both read and write field?JPG
@ArakkalAbu it's a read only field– it's coming from another modelaroooo
That's not I meant. whether the common fields are used only in Serialization purpose?JPG
Yeah, they are only used for serialization.aroooo

2 Answers

0
votes

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
0
votes
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 = [...]