django rest framework - 如何为序列化程序

时间:2016-11-29 16:53:54

标签: python django django-rest-framework

我需要在序列化程序中添加一个静态字段。无论传递的对象如何,它应始终返回相同的值。目前我这样实现了它:

class QuestionSerializer(serializers.ModelSerializer):
    type = serializers.SerializerMethodField()

    @staticmethod
    def get_type(obj):
        return 'question'

    class Meta:
        model = Question
        fields = ('type',)

但是有一种更简单的方法,没有SerializerMethodField

4 个答案:

答案 0 :(得分:3)

唯一的选择是覆盖to_representation并在那里添加值:

def to_representation(self, obj):
    data = super().to_representation(obj)
    data['type'] = 'question'
    return data

虽然不是更好的选择。

答案 1 :(得分:1)

如果您不在乎为模型添加线条,那么将静态字段添加到模型中会更容易。

class Question(models.Model):
    type = 'question'

class QuestionSerializer(serializers.ModelSerializer):

    class Meta:
        model = Question
        fields = ('type',)

答案 2 :(得分:1)

您可以使用serializers.HiddenField

class QuestionSerializer(serializers.ModelSerializer):
type = serializers.HiddenField(default='question')

class Meta:
    model = Question
    fields = ('type',)

http://www.django-rest-framework.org/api-guide/fields/#hiddenfield

答案 3 :(得分:0)

使用ReadOnlyField对我有用:

class QuestionSerializer(serializers.ModelSerializer):
    type = serializers.ReadOnlyField(default='question')

    class Meta:
        model = Question
        fields = ('type',)

https://www.django-rest-framework.org/api-guide/fields/#readonlyfield