Home > database >  PrimaryKeyRelatedField does not serialize the object
PrimaryKeyRelatedField does not serialize the object

Time:07-25

I have a game model like this:

class Game(models.Model):
    owner = models.ForeignKey(User, null=True, blank=True, on_delete=models.SET_NULL)
    name = models.CharField(max_length=255)
    slug = models.SlugField()
    ...

And a serializer like this:

class GameSerializer(serializers.ModelSerializer):
    owner = serializers.PrimaryKeyRelatedField(many=False, read_only=True)
    class Meta:
        model = Game
        fields = (
            "id",
            "name",
            "description",
            "owner"
        )

When I make a request I get this:

description: "TestDescription"
name: "TestName"
owner: 1

I was expecting owner to be a dictionary with fields like an email, a username and so forth. What is wrrong?

CodePudding user response:

PrimaryKeyRelatedField will only give you the primary key (https://www.django-rest-framework.org/api-guide/relations/#primarykeyrelatedfield), not a dict. What you want to do is to define:

class UserSerializer(serializers.ModelSerializer):
    class Meta:
        model = User
        fields = ("username", "email", "first_name", "last_name")

And use that in GameSerializer:

class GameSerializer(serializers.ModelSerializer):
    class Meta:
        model = Game
        fields = ("id", "name", "description", "owner")

    owner = UserSerializer()
  • Related