Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django serializer inherit and extend fields

Tags:

django

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.

like image 973
Zygro Avatar asked Apr 18 '18 13:04

Zygro


2 Answers

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',) 
like image 52
Ganesh Negi Avatar answered Oct 12 '22 12:10

Ganesh Negi


we can do like

class AdvandedSerializer(BasicSerializer):     # ... some code      class Meta:          model = MyModel          fields = BasicSerializer.Meta.fields + ('additional_field',) 
like image 45
anjaneyulubatta505 Avatar answered Oct 12 '22 12:10

anjaneyulubatta505