我想用Django REST Framework保存一个简单的模型.唯一的要求是UserVote.created_by
在perform_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
,而是在代码中自动设置此字段?
提前致谢!
我有类似的问题,我通过显式创建并将新实例传递给序列化程序来解决它.在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)