当前位置:  开发笔记 > 编程语言 > 正文

Django REST框架:"此字段是必需的." with required = False和unique_together

如何解决《DjangoREST框架:"此字段是必需的."withrequired=False和unique_together》经验,为你挑选了1个好方法。

我想用Django REST Framework保存一个简单的模型.唯一的要求是UserVote.created_byperform_create()方法中自动设置.这个例外失败了:

{
    "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)

如何在没有用户提供的情况下将模型保存在DRF中created_by,而是在代码中自动设置此字段?

提前致谢!



1> SimoV8..:

我有类似的问题,我通过显式创建并将新实例传递给序列化程序来解决它.在UserVoteViewSet你必须替换perform_createcreate:

 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)


干净利落!奇迹般有效!非常感谢您的提示!
推荐阅读
LEEstarmmmmm
这个屌丝很懒,什么也没留下!
DevBox开发工具箱 | 专业的在线开发工具网站    京公网安备 11010802040832号  |  京ICP备19059560号-6
Copyright © 1998 - 2020 DevBox.CN. All Rights Reserved devBox.cn 开发工具箱 版权所有