Django Rest Framework ModelSerialzer字段不尊重required = False

时间:2015-05-12 00:57:23

标签: django django-rest-framework

使用django rest framework 3.1.1,我有以下序列化器:

//main function version II
int main(){
   std::vector<int> bigdata1;
   std::vector<int> bigdata2;

   std::thread t1; // Can I do this without telling t1 the function 
                   // to be executed?

   for(int i=0; i<10; ++i){
       // main thread prepare small chunk smalldata1 from bigdata1 for func1;

       if(t1 is ready to execute a function){t1(func1, std::ref(smalldata1));}

       // main thread do other stuff, and prepare small chunk smalldata2 from bigdata2 for func2;

       if (func1 in t1 is done){ 
            t1(func2, std::ref(smalldata2)); 
       }
   }

   t1.join();
   return 0;      
}

虽然class CommentSerializer(ContentSerializer): created_by = UserSerializer(required=False) content = serializers.PrimaryKeyRelatedField(queryset=Content.objects.all(), required=False) class Meta: model = Comment 字段尊重content参数,但required=False没有,这导致我在UserSerializer中为我提供了“此字段是必需的”验证错误列表:

created_by

根据documentation部分“处理嵌套对象”,它演示了序列化程序的用法。

我尝试了什么:

  • 我之前的question关于此问题并尝试添加{"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."]}} 并没有帮助,因为我相信它已经在issue中出现了。

  • 将created_by更改为get_validation_exclusions有效,但这不是我想要的。

  • 在现有问题中快速搜索显示我不是唯一遇到此问题的人: https://github.com/tomchristie/django-rest-framework/issues/2719

更新

我创建了几个测试用例(请参阅here),但无法复制该问题,看起来只是通过Ajax Post发生。

1 个答案:

答案 0 :(得分:0)

我将read_only=True添加到created_by字段,现在它正常工作。

class CommentSerializer(ContentSerializer):

    created_by = UserSerializer(required=False, read_only=True)
    content = serializers.PrimaryKeyRelatedField(queryset=Content.objects.all(), required=False)

    class Meta:
        model = Comment