gpt4 book ai didi

python - Django REST 框架 : "This field is required." with required=False and unique_together

转载 作者:太空狗 更新时间:2023-10-29 22:18:31 26 4
gpt4 key购买 nike

我想用 Django REST Framework 保存一个简单的模型。唯一的要求是 UserVote.created_byperform_create() 方法中自动设置。失败并出现以下异常:

{
"created_by": [
"This field is required."
]
}

我猜这是因为 unique_together 索引。

模型.py:

class UserVote(models.Model):
created_by = models.ForeignKey(User, related_name='uservotes')
rating = models.ForeignKey(Rating)

class Meta:
unique_together = ('created_by', 'rating')

序列化器.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')

View .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 而是在代码中自动设置此字段?

提前致谢!

最佳答案

我有一个类似的问题,我通过显式创建一个新实例并将其传递给序列化程序来解决它。在 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)

关于python - Django REST 框架 : "This field is required." with required=False and unique_together,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34661853/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com