[Django]-How to get string representation of PrimaryKeyRelatedField in JSON

7πŸ‘

βœ…

To do that, you need to override the to_representation() method of PrimaryKeyRelatedField as it returns the pk.

You can create a MyPrimaryKeyRelatedField which inherits from PrimaryKeyRelatedField and then override its to_representation() method.

Instead of value.pk which PrimaryKeyRelatedField returned, return the string representation now. I have used six.text_type() instead of str() to handle both the Python 2(unicode) and Python 3(str) versions.

from django.utils import six
from rest_framework import serializers

class MyPrimaryKeyRelatedField(serializers.PrimaryKeyRelatedField):

    def to_representation(self, value):
        return six.text_type(value) # returns the string(Python3)/ unicode(Python2) representation now instead of pk 

Your serializers.py would then look like:

class MovieSerializer(serializers.ModelSerializer):
    """
    Serialiazing all the Movies.
    """
    genre = MyPrimaryKeyRelatedField(many=True, queryset=Genre.objects.all())
    directorName = MyPrimaryKeyRelatedField(queryset=Director.objects.all())
    owner = serializers.ReadOnlyField(source='owner.username')
    class Meta:
        model = Movie
        fields = ('popularity',"directorName",'genre','imdbScore','name','owner')

3πŸ‘

The simplest is probably to use StringRelatedField

class MovieSerializer(serializers.ModelSerializer):
    directorName = serializers.StringRelatedField(many=True)

class Director(Model):
    # [...]
    def __unicode__(self):
        return self.directorName

However, that does not work when you need different representations of the Director model. In that case you need to go with a custom serializer (see answer from Rahul Gupta).

Leave a comment