django restful-framework显示格式

时间:2014-12-18 00:39:11

标签: python django django-rest-framework

我有一个端点,可以给出这样的响应

 "trailer": [
                {
                    "trailerurl": "http://www.you/1"
                }, 
                {
                    "trailerurl": "http://www.you/2"
                }, 
                {
                    "trailerurl": "http://www.you/3"
                }
            ]

我有兴趣得到这样的回复,没有包裹网址的对象

  "trailer": [
                 "http://www.you/1", 
                 "http://www.you/2", 
                 "http://www.you/3"
            ]

以下是我当前的序列化程序

class MovieSerializer(serializers.ModelSerializer):
    trailer = MovieTrailerSerializer(many=True, read_only=True, source='trailer_set')
    class Meta:
        model = Movie
        fields = ('trailer',)


class MovieTrailerSerializer(serializers.ModelSerializer): 
    class Meta:
        model = Trailer
        fields = (  'trailerurl', ) 

1 个答案:

答案 0 :(得分:0)

您可以使用SerializerMethodField

执行此操作
class MovieSerializer(serializers.ModelSerializer):
    trailer = serializers.SerializerMethodField()

    class Meta:
        model = Movie
        fields = ('trailer',)

    def get_trailer(self, obj):
        trailers = []

        for trailer in obj.trailer_set.all():
            trailers.append(trailer.trailerurl)

        return trailers