python – Django REST框架:“此字段是必需的.”with required
发布时间:2020-12-16 23:34:32 所属栏目:Python 来源:网络整理
导读:我想用Django REST Framework保存一个简单的模型.唯一的要求是在perform_create()方法中自动设置UserVote.created_by.这个例外失败了: { "created_by": [ "This field is required." ]} 我想这是因为unique_together索引. models.py: class UserVote(model
我想用Django REST Framework保存一个简单的模型.唯一的要求是在perform_create()方法中自动设置UserVote.created_by.这个例外失败了:
{ "created_by": [ "This field is required." ] } 我想这是因为unique_together索引. models.py: class UserVote(models.Model): created_by = models.ForeignKey(User,related_name='uservotes') rating = models.ForeignKey(Rating) class Meta: unique_together = ('created_by','rating') serializers.py class UserVoteSerializer(serializers.ModelSerializer): id = serializers.IntegerField(read_only=True) created_by = UserSerializer(read_only=True) class Meta: model = UserVote fields = ('id','rating','created_by') views.py class UserVoteViewSet(viewsets.ModelViewSet): queryset = UserVote.objects.all() serializer_class = UserVoteSerializer permission_classes = (IsCreatedByOrReadOnly,) def perform_create(self,serializer): serializer.save(created_by=self.request.user) 如何在不让用户提供created_by的情况下将模型保存在DRF中,而是在代码中自动设置此字段? 提前致谢! 解决方法
我有类似的问题,我通过显式创建并将新实例传递给序列化程序来解决它.在UserVoteViewSet中,您必须将perform_create替换为create:
def create(self,request,*args,**kwargs): uv = UserVote(created_by=self.request.user) serializer = self.serializer_class(uv,data=request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data,status=status.HTTP_201_CREATED) else: return Response(serializer.errors,status=status.HTTP_400_BAD_REQUEST) (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |