Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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
like image 858
Papa Sax Avatar asked Sep 09 '13 10:09

Papa Sax


People also ask

How do you pass extra context data to Serializers in Django REST Framework?

In function-based views, we can pass extra context to serializer with “context” parameter with a dictionary. To access the extra context data inside the serializer we can simply access it with “self. context”. From example, to get “exclude_email_list” we just used code 'exclude_email_list = self.

What is the difference between ModelSerializer and HyperlinkedModelSerializer?

The HyperlinkedModelSerializer class is similar to the ModelSerializer class except that it uses hyperlinks to represent relationships, rather than primary keys. By default the serializer will include a url field instead of a primary key field.

Do we need Serializers in Django REST Framework?

Serializers in Django REST Framework are responsible for converting objects into data types understandable by javascript and front-end frameworks. Serializers also provide deserialization, allowing parsed data to be converted back into complex types, after first validating the incoming data.


1 Answers

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

like image 138
benspaulding Avatar answered Sep 28 '22 16:09

benspaulding