Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
540 views
in Technique[技术] by (71.8m points)

Django serializer inherit and extend fields

I have these 2 serializers:

class BasicSerializer(serializers.ModelSerializer):
    class Meta:
         model = MyModel
         fields = ('lengthy', 'touple', 'of', 
              'fields', 'like', '10', 'of', 'them')

class AdvandedSerializer(BasicSerializer):
    additional_field = serializers.SerializerMethodField()
    def get_additional_field(self, obj):
        return('not important')
    class Meta:
         model = MyModel
         fields = ('lengthy', 'touple', 'of', 
              'fields', 'like', '10', 'of', 'them', 'additional_field')       

This is obviously rather ugly code. I would like to get and extend the fields touple from super(), however I have no idea how.

question from:https://stackoverflow.com/questions/49900629/django-serializer-inherit-and-extend-fields

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You can do:

class BasicSerializer(serializers.ModelSerializer):
    class Meta:
         model = MyModel
         fields = ('lengthy', 'touple', 'of', 'fields', 'like', '10', 'of', 'them')

class AdvandedSerializer(BasicSerializer):
    additional_field = serializers.SerializerMethodField()

    def get_additional_field(self, obj):
        return('not important')

    class Meta(BasicSerializer.Meta):
        fields = BasicSerializer.Meta.fields + ('additional_field',)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...