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

Viewed 35

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.

model:

class Run(models.Model):
    gameId = models.ForeignKey(Game,on_delete=models.CASCADE, related_name='runs')
    userId = models.ForeignKey(User,on_delete=models.CASCADE, related_name='game')
    name = models.CharField(max_length=30)
    isComplete = models.BooleanField(default=False)
    deaths = models.IntegerField()
    badges = models.IntegerField()
    def __str__(self):
        return self.name

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

1 Answers

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)
Related