Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
688 views
in Technique[技术] by (71.8m points)

python - Dynamically modifying serializer fields in Django Rest Framework

I'm trying to use the Advanced serializer usage described in the django rest framework documentation. http://django-rest-framework.org/api-guide/serializers.html#advanced-serializer-usage to dynamically modifying serializer field

Here is my serializer class:

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')

Here is my viewset

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

I get this error:

TypeError: 'MovieSerializer' object is not callable
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Note that you are setting serializer_class not to a class, but to an instance of the class. You either need to set dropfields as an attribute on the class, (just like it does for fields in the documented example you link to) or you need to look at overriding the get_serializer method of the viewset (docs).


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

56.8k users

...