来自Serializer DRF中数据的非模型字段

时间:2019-03-22 08:39:08

标签: python django python-3.x serialization django-rest-framework

我正在尝试序列化对象,以便将非模型字段的数据传递给序列化器

    data = {
        'field1': 'abc',
        'field2': 123,
    }

    serializer = UserSerializer(
        user,
        context={"request": request},
        data=request.data,
        partial=True,
    )
    serializer.is_valid(raise_exception=True)
    result = serializer.validated_data

我有一个这样的UserSerializer

class UserSerializer(serializers.ModelSerializer):
    field1 = serializers.SerializerMethodField()
    field2 = serializers.SerializerMethodField()

    class Meta:
        model = User
        fields = (
            'username',
            'field1',
            'field2',
        )

但是我从DefaultDict()中空了serializer.validated_data

1 个答案:

答案 0 :(得分:1)

您需要定义serializerMethod。喜欢

class UserSerializer(serializers.ModelSerializer):
    field1 = serializers.SerializerMethodField()
    field2 = serializers.SerializerMethodField()

    class Meta:
        model = User
        fields = (
            'username',
            'field1',
            'field2',
        )

    def get_field1(self, obj):
        value = self.context['request'].data.get('field1')
        return value
    def get_field2(self, obj):
        value = self.context['request'].data.get('field2')
        return value