I have a case where the values for a serializer field depend on the identity of the currently logged in user. I have seen how to add the user to the context when initializing a serializer, but I am not sure how to do this when using a ViewSet, as you only supply the serializer class and not the actual serializer instance.
Basically I would like to know how to go from:
class myModelViewSet(ModelViewSet): queryset = myModel.objects.all() permission_classes = [DjangoModelPermissions] serializer_class = myModelSerializer
to:
class myModelSerializer(serializers.ModelSerializer): uploaded_by = serializers.SerializerMethodField() special_field = serializers.SerializerMethodField() class Meta: model = myModel def get_special_field(self, obj): if self.context['request'].user.has_perm('something.add_something'): return something
Sorry if it wasn't clear, from the DOCs: Adding Extra Context Which says to do
serializer = AccountSerializer(account, context={'request': request}) serializer.data
But I am not sure how to do that automatically from the viewset, as I only can change the serializer class, and not the serializer instance itself.
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.
Django REST framework allows you to combine the logic for a set of related views in a single class, called a ViewSet . In other frameworks you may also find conceptually similar implementations named something like 'Resources' or 'Controllers'.
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.
The ModelSerializer class is the same as a regular Serializer class, except that: It will automatically generate a set of fields for you, based on the model. It will automatically generate validators for the serializer, such as unique_together validators. It includes simple default implementations of .
GenericViewSet
has the get_serializer_context
method which will let you update context
:
class myModelViewSet(ModelViewSet): queryset = myModel.objects.all() permission_classes = [DjangoModelPermissions] serializer_class = myModelSerializer def get_serializer_context(self): context = super(myModelViewSet, self).get_serializer_context() context.update({"request": self.request}) return context
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