将URL参数传递给嵌套的序列化程序

时间:2015-12-08 21:15:06

标签: python django api django-rest-framework

我有两个序列化程序,其中一个是嵌套的:

class PaperSerializer(serializers.ModelSerializer):

    class Meta:
        model = Paper


class AuthorSerializer(serializers.ModelSerializer):
    papers = PaperSerializer(
        many=True,
        read_only=True,
        source='paper_set'
    )

    class Meta:
        model = Author

我想获得一份作者列表,其中只显示了已发布的论文(模型上存在布尔字段)。

我想将API称为/api/v1/authors/?show_published_only=true

1 个答案:

答案 0 :(得分:1)

经过一番挖掘,我发现你可以将上下文从ViewSet传递给Serializer:

<强> views.py

class AuthorViewSet(viewsets.ModelViewSet):
    queryset = Author.objects.all()
    serializer_class = AuthorSerializer
    filter_fields = (
        'show_published_only',
    )

    def get_serializer_context(self):
        return {'request': self.request}

现在,创建一个继承自FilteredPaperSerializer的新序列化程序serializers.ListSerializer,然后覆盖to_representation()方法以过滤查询集:

<强> serializers.py

class FilteredPaperSerializer(serializers.ListSerializer):
    def to_representation(self, data):
        # Get the parameter from the URL
        show_published_only = self.context['request'].query_params['show_published_only']

        data = data.filter(is_published=show_published_only)
        return super(FilteredPaperSerializer, self).to_representation(data)

class AuthorSerializer(serializers.ModelSerializer):
    papers = FilteredPaperSerializer(
        many=True,
        read_only=True,
        source='paper_set'
    )

    class Meta:
        model = Author

NB:不要忘记将获取的网址参数转换为模型的布尔值或相关数据类型,我忽略了在上面的文字中进行此操作。