对序列化程序中的序列化程序没有require = False的影响

时间:2018-12-13 14:13:26

标签: django django-rest-framework

序列化器:

class AvatarBaseSerializer(Serializer):
    uuid = ReadOnlyField()
    user = UserBaseSerializer(read_only=True)
    name = CharField(allow_blank=True)
    GENDER = (("M", "Man"), ("W", "Woman"))
    gender = ChoiceField(choices=GENDER)
    body = BodySerializer(partial=True, required=False)
    head = HeadBaseSerializer(read_only=True)
    head_pk = IntegerField(write_only=True)
    head_adjust = HeadAdjustBaseSerializer(partial=True, required=False)
    hair = HairBaseSerializer(read_only=True)
    hair_pk = UUIDField(write_only=True)
    hair_adjust = HairAdjustBaseSerializer(partial=True, required=False)
    thumbnail = ImageField(required=False, allow_null=True) 

视图集:

class AvatarViewSet(viewsets.ModelViewSet):
    queryset = Avatar.objects.all()
    serializer_class = AvatarBaseSerializer
    permission_classes = (permissions.UserIsRequestUserPermission,)

    ...

    def partial_update(self, request, *args, **kwargs):
        self.check_thumbnail_file_size(request)
        return super().partial_update(request, *args, **kwargs)

我用PATCH方法发送以下参数。但是Django rest框架会返回400 Bad Request(“无效输入”)。

{
  "head_pk": 1,
  "hair_pk": "89d4c318-c9bf-42cd-b4c4-b7e70a2c8f40",
  "name": "gewgew",
  "gender": "W"
}

我要发送的参数不包括body,head_adjust和hair_adjust。

1 个答案:

答案 0 :(得分:0)

将验证应用于ModelSerializer时,序列化程序字段及其对应的模型字段都必须正确验证。如果模型上有可选字段,请确保在模型字段上正确设置blank=True,并在序列化器字段上设置required=False

you can see it in Docs