Django序列化程序继承并扩展字段

时间:2018-04-18 13:11:37

标签: django

我有这两个序列化器:

ConcurrentMap

这显然是相当丑陋的代码。我想从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') 获取并扩展fields touple,但我不知道如何。

2 个答案:

答案 0 :(得分:6)

你可以这样做:

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',)

答案 1 :(得分:4)

我们可以这样做

class AdvandedSerializer(BasicSerializer):
    # ... some code

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