我使用的是Django REST框架,我对这件事还很陌生。
我想在JSON输出中使用manytomanyfield和foreignkey字段的字符串表示,而不是值。
模型.py
class Movie(models.Model):
"""Movie objects"""
name = models.CharField(max_length=128)
directorName = models.ForeignKey(Director)
genre = models.ManyToManyField(Genre)
序列化程序.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输出
{"popularity":"90.0","directorName":1,"genre":[1,2,3],"imdbScore":"8.9","name":"Titanic"}
与directorName和genre的显示名不同,我只得到值。
请建议我如何改正这个错误。
编辑
[已解决]
您需要重写PrimaryKeyRelatedField的to_representation()方法,因为它返回pk。
最佳答案
为此,需要重写to_representation()
的PrimaryKeyRelatedField
方法,因为它返回pk
。
您可以创建一个继承自MyPrimaryKeyRelatedField
的PrimaryKeyRelatedField
,然后重写其to_representation()
方法。
现在返回字符串表示,而不是返回value.pk
的PrimaryKeyRelatedField
。我使用six.text_type()
而不是str()
来处理Python 2(unicode)和Python 3(str)版本。
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
然后您的
serializers.py
看起来像: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')