带有PATCH请求的serializer.update中的DRF CurrentUserDefault

时间:2018-10-19 13:42:08

标签: django django-rest-framework

PATCH请求下,带有{'description': 'product_3'}的序列化程序在经过验证的数据中不包含user

如何在不调用CurrentUserDefault()的情况下将.save(updated_by=request.user)添加到经过验证的数据中?

class MySerializer(serializer.ModelSerializer):
    user = serializers.HiddenField(default=serializers.CurrentUserDefault())

    class Meta:
        model = Model
        fields = ('id', 'user', 'description')

    def create(self, validated_data):
        validated_data['created_by'] = validated_data.pop('user')
        return super().create(validated_data)

    def update(self, instance, validated_data):
        validated_data['updated_by'] = validated_data.pop('user')
        return super().create(instance, validated_data)

1 个答案:

答案 0 :(得分:0)

CurrentUserDefault()

def update(self, instance, validated_data):
    user = validated_data.pop('user', None)
    validated_data['updated_by'] = user if user else self.fields['user'].context['request'].user
    return super().update(instance, validated_data)