ModelSerializer中的get_extra_kwargs方法对嵌套序列化程序的read_only参数没有影响

时间:2018-04-06 16:02:28

标签: django-rest-framework

我尝试仅在创建对象时允许使用带有序列化程序的嵌套对象进行操作。但是使用以下代码嵌套的inputoutput字段仍以html格式显示(但没有嵌套字段)并在我尝试更新唯一可调"error": "{'output': ['This field is required.'], 'input': ['This field is required.']}"字段时抛出status

enter image description here

class OrderSerializer(serializers.ModelSerializer):
    input = InputSerializer()
    output = OutputSerializer()

    def get_extra_kwargs(self):

        extra_kwargs = super().get_extra_kwargs()
        _request = self.context['view'].request
        all_fields = (
            'id',
            'input',
            'output',
            'status',
        )
        adjustable_fields = []
        if _request.method == 'PUT':
            _rs = _request.parser_context['kwargs'].get('random_string')
            if _rs:
                adjustable_fields = [
                    'status',
                ]
            elif _request.user.is_staff:
                adjustable_fields = [
                    'input',
                    'status',
                    'custom_rate',
                    'custom_min_profit',
                    'custom_service_fee_percent'
                ]
            else:
                adjustable_fields = []
        extra_kwargs.update({x: {'read_only': True} for x in all_fields if x not in adjustable_fields})
        return extra_kwargs

UPD 我没有登录样本

0 个答案:

没有答案