"Incorrect type. Expected pk value, received list." Error DRF React

Viewed 621

Error when attempting post request Many to Many Relation

Question is

when I put list in request It shows an Error: "Incorrect type. Expected pk value, received list." .But it is m2m field so how can i

View

class PostList(generics.ListCreateAPIView):
    queryset = Post.objects.all()
    serializer_class = serializers.PostSerializer
    permission_classes = [permissions.IsAuthenticatedOrReadOnly]
    parser_classes = (MultiPartParser, FormParser)

    def post(self, request, *args, **kwargs):
        print(request.data['categories'])
        file_serializer = serializers.PostSerializer(data=request.data)
        print(request.data.dict())
        if file_serializer.is_valid():
                print(request.data)
                file_serializer.save(owner=self.request.user)
                return Response(file_serializer.data, status=status.HTTP_201_CREATED)
        else:
                return Response(file_serializer.errors, status=status.HTTP_400_BAD_REQUEST)

Serializer

class PostSerializer(serializers.ModelSerializer):
    owner = serializers.ReadOnlyField(source='owner.username')
    comments = serializers.PrimaryKeyRelatedField(many=True,queryset=Comment.objects.all())
    categories = serializers.PrimaryKeyRelatedField(many=True,queryset=Category.objects.all())

    class Meta:
        model = Post
        fields = ['id', 'title', 'body','owner','notify_users' ,'comments', 'categories','image']
 

Request I send

{
'title': 'my demo Title',
 'body': 'it is my demo /nCode for the desc for body',
 'categories': ['1', '2', '3', '4', '5', '6', '7'],
 'image': image
}

No error with this Code

{
'title': 'my demo Title',
 'body': 'it is my demo /nCode for the desc for body',
 'categories': '1',
 'image': image
}

GitHub Repo

2 Answers

I am also facing the same issue when I try to add the owner field manually in request.data.

my serializer class

fields = ("file", "name", "size", "owner")

in my views

request.data['owner'] = request.user
file_serializer = FileSerializer(data=request.data)
    if file_serializer.is_valid():
        file_serializer.save()

in my Model

owner = models.OneToOneField(User, primary_key=True, on_delete=models.CASCADE)

Here is some code that should help. m2m field cannot be created automatically. It has to be added to the object. Also you can see categories are being created one by one and not using bulk_create which is not recommended.

class PostSerializer(serializers.ModelSerializer):
    owner = serializers.ReadOnlyField(source='owner.username')
    comments = serializers.PrimaryKeyRelatedField(many=True,queryset=Comment.objects.all())
    categories = CategoriesSerializer(many=True)

    class Meta:
        model = Post
        fields = ['id', 'title', 'body','owner','notify_users' ,'comments', 'categories','image']
        
    def create(self, validated_data):
        categories = validated_data.pop("categories", [])
        post = Post.objects.create(**validated_data)
        for category in categories:
            post.categories.create(**category)
        return post
Related