I'm using Django REST Framework and I'm fairly newbie to this thing.
I want to have string representation for the manytomanyfield and foreignkey fields in my JSON output rather than the value.
models.py
class Movie(models.Model):
"""Movie objects"""
name = models.CharField(max_length=128)
directorName = models.ForeignKey(Director)
genre = models.ManyToManyField(Genre)
serializers.py
class MovieSerializer(serializers.ModelSerializer):
"""
Serialiazing all the Movies.
"""
genre = serializers.PrimaryKeyRelatedField(many=True, queryset=Genre.objects.all())
directorName = serializers.PrimaryKeyRelatedField(queryset=Director.objects.all())
owner = serializers.ReadOnlyField(source='owner.username')
class Meta:
model = Movie
fields = ('popularity',"directorName",'genre','imdbScore','name','owner')
JSON output
{"popularity":"90.0","directorName":1,"genre":[1,2,3],"imdbScore":"8.9","name":"Titanic"}
instead of directorName's and genre's display_name, I'm getting only the values.
Please suggest me how to correct this.
EDIT [SOLVED] You need to override the to_representation() method of PrimaryKeyRelatedField as it returns the pk.
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')
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).
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.