Why can i not add object into field rest_framework

I want to add some objects using rest_framework serializers but I am getting this error from the serializer. I See some people with the same but I don't know how to fix it in my situation.

    "user": [
        "Incorrect type. Expected pk value, received str."

Of course, I read the documentation about serializers and relation but I still don't understand.. newbie in django

Here my models

class UserData(AbstractUser):

    username = None
    name = models.CharField(max_length=100, unique=True)
    email = models.EmailField(max_length=100, unique=True)
    date_joined = models.DateTimeField(auto_now_add=True)
    pseudo = models.CharField(max_length=200,unique=True)
    hashtag = models.CharField(max_length=200, unique=True)
    is_admin = models.BooleanField(default=False)
    is_active = models.BooleanField(default=True)
    is_staff = models.BooleanField(default=False)
    is_superuser = models.BooleanField(default=False)
    objects = UserManager()
    USERNAME_FIELD = "pseudo"
    REQUIRED_FIELDS = ['name','hashtag','email']

    def __str__(self):
        return self.name

class Pebbles(models.Model):
    image = models.CharField(max_length=200)
    user = models.ForeignKey(UserData, related_name="pebbles",on_delete=models.CASCADE)

    class Meta():
        unique_together = ["id","user"]

I can get a list of pebbles from that view it works.

class PebblesView(generics.ListCreateAPIView):
    permission_classes = [IsAuthenticated]
    authentication_classes = [JWTAuthentication]
    serializer_class = PebblesSerializer

    def get_queryset(self):
        return Pebbles.objects.all()
    def create(self, request):
        serializer = PebblesSerializer(data=request.data)
        return Response(serializer.data)

I can register a user with my UserSerializer. I have the same logic for pebbles but it doesn't work. In the Django shell, I can create pebbles just like this.

class UserSerializer(serializers.ModelSerializer):
    pebbles = serializers.StringRelatedField(many=True)

    class Meta:
        model = UserData
        fields = ["id", "pseudo", "hashtag","email", "name", "password","pebbles"]

    def create(self, validated_data):
        user = UserData.objects.create(
        return user

class PebblesSerializer(serializers.ModelSerializer):

    class Meta:
        model = Pebbles
        fields = ["id","image","user"]

    def create(self, request):
        pebbles = Pebbles.objects.create(
        return pebbles

Can someone give me a hint ?

I didn't understand that Django rest framework go so far in automation.


It already contains the UserData object so no need to search for it. And I do make a mistake using the pseudo field instead id.

Back to Top