Django REST Framework : “This field is required.” with required=False and unique_together

I want to save a simple model with Django REST Framework. The only requirement is that UserVote.created_by is set automatically within the perform_create() method. This fails with this exception:

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

I guess it is because of the unique_together index.

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)

How can I save my model in DRF without having the user to supply created_by and instead set this field automatically in code?

Thanks in advance!

Best answer

I had a similar problem and I solved it by explicitly creating and passing a new instance to the serializer. In the UserVoteViewSet you have to substitute perform_create with 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)