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
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.
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.
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.
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).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With