python – Django REST框架:“此字段是必需的.”with required = False和unique_together

前端之家收集整理的这篇文章主要介绍了python – Django REST框架:“此字段是必需的.”with required = False和unique_together前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我想用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)
原文链接:https://www.f2er.com/python/185769.html

猜你在找的Python相关文章