根据基本请求参数删除HyperlinkedModelSerializer的ForeignKey的字段

时间:2016-08-21 19:19:15

标签: django django-rest-framework

目前我有:

class PlayerSerializer(serializers.HyperlinkedModelSerializer):
    id = serializers.ReadOnlyField()

    class Meta:
        model = Player

    def __init__(self, *args, **kwargs):
        super(PlayerSerializer, self).__init__(*args, **kwargs)

        self.is_full = self.context['request'].query_params.get('full', False)

        if not self.is_full:
            base_fields = ['nation', 'club', 'slug', 'common_name', 'image', 'position', 'quality', 'overall_rating',
                           'card_att_1', 'card_att_2', 'card_att_3', 'card_att_4', 'card_att_5', 'card_att_6']

            for field in self.fields:
                if field not in base_fields:
                    self.fields.pop(field)

        self.fields['nation'] = NationSerializer(is_full=self.is_full)
        self.fields['league'] = LeagueSerializer(is_full=self.is_full)
        self.fields['club'] = ClubSerializer(is_full=self.is_full)

哪个正常,但ClubSerializer

class ClubSerializer(serializers.HyperlinkedModelSerializer):
    id = serializers.ReadOnlyField()
    league = LeagueSerializer()

我希望LeagueSerializer根据请求查询参数的值来设置字段。是不是只是将它作为kwarg传递并对每个Serializer进行self.is_full = self.context['request'].query_params.get('full', False)检查?

1 个答案:

答案 0 :(得分:1)

我对每个序列化程序都进行了检查,所以即使我没有手动构建序列化程序(例如在ViewSet s中),逻辑也能正常工作。