在Django Rest Framework中动态修改序列化器字段

前端之家收集整理的这篇文章主要介绍了在Django Rest Framework中动态修改序列化器字段前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

我正在尝试使用django rest框架文档中描述的高级序列化程序用法. http://django-rest-framework.org/api-guide/serializers.html#advanced-serializer-usage动态修改序列化器字段

这是我的序列化程序类:

class MovieSerializer(serializers.ModelSerializer):
    moviework_work = MovieWorkSerializer(many=True) 

    def __init__(self,*args,**kwargs):
        # Don't pass the 'fields' arg up to the superclass
        dropfields = kwargs.pop('dropfields',None)

        # Instantiate the superclass normally
        super(MovieSerializer,self).__init__(*args,**kwargs)

        if dropfields:
            # Drop fields specified in the `fields` argument.
            banished = set(dropfields)
            for field_name in banished:
                self.fields.pop(field_name)
    class Meta:
        model = Movie
        fields = ('field1','field2','moviework_work')

这是我的观点

class MovieFromInterpreterViewSet(viewsets.ModelViewSet):
    queryset = Movie.objects.all()
    serializer_class = MovieSerializer(dropfields=('moviework_work',))

我收到此错误

TypeError: 'MovieSerializer' object is not callable
最佳答案
请注意,您将serializer_class设置为不是类,而是设置为类的实例.您需要将dropfields设置为类的属性(就像它链接到的文档示例中的字段一样),或者您需要查看覆盖视图集的get_serializer方法(docs).
原文链接:/python/439615.html

猜你在找的Python相关文章