I have those two seralizers based on following models:

class LanguageSerializer(serializers.ModelSerializer):

    class Meta:
        model = Language
        fields = '__all__'


class GameSerializer(serializers.ModelSerializer):
    language = LanguageSerializer()

    class Meta:
        model = Game
        fields = '__all__'


class Game(models.Model):
    language = models.ForeignKey(Language)


class Language(models.Model):
    name = models.CharField(max_length=50, unique=True)
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)

When I try to create a new Game entity, I pass as parameter the Language id of this Game. For some reasons, DRF is expecting the language to be passed as a dictionary and not as an integer. Here is the error:

{
    "language": {
        "non_field_errors": [
            "Invalid data. Expected a dictionary, but got int."
        ]
    }
}

What is the proper way to indicate to DRF, to create a Game which has the Language property based on the provided Language id ?

score:1

Creating a separate serializer that doesn't include all of the details about Language is one solution. You can create a separate serializer that uses the PrimaryKeyRelatedField()

# I always call mine shallow to differentiate between the full serializer
class ShallowGameSerializer(serializers.ModelSerializer):
    language = serializers.PrimaryKeyRelatedField()
    class Meta:
        model = Game
        fields = '__all__'

You can use the normal GameSerializer when returning/listing objects, and then the ShallowGameSerializer when creating a Game, allowing you to just provide the id.


Related Query