Getting null value in column "userId_id" of relation "pnrDB_run when sending a POST to django backend

Still very new to Django. I'm trying to send a post request to my backend from insomnia right now and I'm getting the error Getting null value when I'm passing in the ID value.

Here is my seralizer:

class RunSerialzer(serializers.HyperlinkedModelSerializer):
gameId = GameSerialzer(
    read_only = True
)
userId = UserSerialzer(
    read_only = True  
)
class Meta:
    model = Run
    fields=('id','name','isComplete','deaths','badges','userId','gameId')

My view:

class RunList(generics.ListCreateAPIView):
queryset = Run.objects.all()
serializer_class = RunSerialzer

And my request I'm making:

{
"gameId":1,
"userId": 1,
"name":"testrun2",
"deaths":0,
"badges": 0,
"isComplete": false
}

and the second one I tried

{
"gameId": {
        "id": 1,
        "name": "Vintage White",
        "photo": "https://archives.bulbagarden.net/media/upload/thumb/0/08/White_EN_boxart.png/250px-White_EN_boxart.png"
    },
"userId": {
        "id": 1,
        "name": "TestUser"
    },
"name":"testrun2",
"isComplete": false,
"deaths": 0,
"badges": 0
}

I feel like I need to create either a new Serailizer to get the instance I want in my Game model with the pk im passing in the request

since you are using read_only=True on your serializer for two of your fields you need to pass gameId and userId manually to save method of serializer.

in your view(RunList) you should overwrite perform_create method like following:

def perform_create(self, serializer):
    gameId = self.request.data.get('gameId')
    userId = self.request.data.get('userId')
    return serializer.save(gameId=gameId, userId=userId)
Back to Top