【问题标题】:Dajngo Rest Framework how to set field to no requiredDjango Rest Framework如何将字段设置为不需要
【发布时间】:2021-07-20 09:39:47
【问题描述】:

我有此代码,我想将content 字段设置为不需要。

type = serializers.ReadOnlyField(default=ComponentType.MediaComponent.value)
content = ContentSerializer()

class Meta:
    model = MediaComponent
    fields = ['id'] + ComponentSerializer.Meta.fields + ['type', 'content']

【问题讨论】:

    标签: python django django-rest-framework


    【解决方案1】:

    在 Meta 类中添加 extra_kwargs 或将 required=false 添加到如下内容序列化程序中

    type = serializers.ReadOnlyField(default=ComponentType.MediaComponent.value)
    content = ContentSerializer(required=False)
    
    class Meta:
        model = MediaComponent
        fields = ['id'] + ComponentSerializer.Meta.fields + ['type', 'content']
    

    或者

    type = serializers.ReadOnlyField(default=ComponentType.MediaComponent.value)
    content = ContentSerializer()
    
    class Meta:
        model = MediaComponent
        fields = ['id'] + ComponentSerializer.Meta.fields + ['type', 'content']
        extra_kwargs = {"content": {"required": False}}
    

    【讨论】:

    • 第一个正在工作,但在第二种方式我有这个错误 {'content': [ErrorDetail(string='This field is required.', code='required')]},
    • 你的负载请求是什么?
    猜你喜欢
    • 2019-05-22
    • 2018-04-15
    • 2014-08-18
    • 2015-07-28
    • 2016-06-01
    • 1970-01-01
    • 1970-01-01
    • 2021-10-03
    • 1970-01-01
    相关资源
    最近更新 更多