Django Rest Framework ModelSerialzer 字段不遵守 required=False
Django Rest Framework ModelSerialzer field doesn't respect required=False
使用 django rest framework 3.1.1,我有以下序列化器:
class CommentSerializer(ContentSerializer):
created_by = UserSerializer(required=False)
content = serializers.PrimaryKeyRelatedField(queryset=Content.objects.all(), required=False)
class Meta:
model = Comment
虽然 content
字段尊重 required=False
参数,但 created_by
不尊重,结果,在 UserSerializer 中给出了 "This field is required" 验证错误列表:
{"created_by":{"username":["This field is required."],"user_permissions":["This field is required."],"password":["This field is required."],"groups":["This field is required."],"profile_picture":["This field is required."]}}
根据 documentation 部分 "Dealing with nested objects" 它演示了序列化程序的用法。
我试过的:
我之前的question about this and tried adding get_validation_exclusions
did not help as I believe it's already been attended in this issue.
将 created_by 更改为 created_by = serializers.PrimaryKeyRelatedField(required=False)
有效,但这不是我想要的。
- 在现有问题中快速搜索显示我不是唯一遇到此问题的人:
https://github.com/tomchristie/django-rest-framework/issues/2719
更新:
我已经创建了几个测试用例(参见 here)但无法重现问题,看起来它只发生在 Ajax Post.
我在 created_by 字段中添加了 read_only=True
,现在可以正常工作了。
class CommentSerializer(ContentSerializer):
created_by = UserSerializer(required=False, read_only=True)
content = serializers.PrimaryKeyRelatedField(queryset=Content.objects.all(), required=False)
class Meta:
model = Comment
使用 django rest framework 3.1.1,我有以下序列化器:
class CommentSerializer(ContentSerializer):
created_by = UserSerializer(required=False)
content = serializers.PrimaryKeyRelatedField(queryset=Content.objects.all(), required=False)
class Meta:
model = Comment
虽然 content
字段尊重 required=False
参数,但 created_by
不尊重,结果,在 UserSerializer 中给出了 "This field is required" 验证错误列表:
{"created_by":{"username":["This field is required."],"user_permissions":["This field is required."],"password":["This field is required."],"groups":["This field is required."],"profile_picture":["This field is required."]}}
根据 documentation 部分 "Dealing with nested objects" 它演示了序列化程序的用法。
我试过的:
我之前的question about this and tried adding
get_validation_exclusions
did not help as I believe it's already been attended in this issue.将 created_by 更改为
created_by = serializers.PrimaryKeyRelatedField(required=False)
有效,但这不是我想要的。- 在现有问题中快速搜索显示我不是唯一遇到此问题的人: https://github.com/tomchristie/django-rest-framework/issues/2719
更新:
我已经创建了几个测试用例(参见 here)但无法重现问题,看起来它只发生在 Ajax Post.
我在 created_by 字段中添加了 read_only=True
,现在可以正常工作了。
class CommentSerializer(ContentSerializer):
created_by = UserSerializer(required=False, read_only=True)
content = serializers.PrimaryKeyRelatedField(queryset=Content.objects.all(), required=False)
class Meta:
model = Comment