Search code examples
djangodjango-rest-frameworkdjango-serializer

Confused when delivering PrimaryKeyRelatedField to the Client


If you extract the value of the field used as PrimaryKeyRelatedField, you will see the value in the form of Object, not PK.

In the case of the official document, I am using it as below, but it is confusing when using it with the client.

I don't know if the tracks will contain id or Object just by looking at the field name.

class AlbumSerializer(serializers.ModelSerializer):
    tracks = serializers.PrimaryKeyRelatedField(many=True, read_only=True)

    class Meta:
        model = Album
        fields = ['tracks']
    
        def create(self, validated_data):
                tracks = validated_data.pop('tracks')  # [Track, Track ...]

Is there a better way?


Solution

  • tracks in tracks = validated_data.pop('tracks') will contain Track objects, because you are getting it from validated_data which uses to_internal_value which in turn gives you the model instance objects.

    You can have a look at PrimaryKeyRelatedField's implementation here:

    https://github.com/encode/django-rest-framework/blob/master/rest_framework/relations.py#L243

    The implementation of to_representation and to_internal_value should give you hints. You can read more here:

    https://www.django-rest-framework.org/api-guide/serializers/#overriding-serialization-and-deserialization-behavior