From 412747d632fbf9f59481ff56ab8e9a46251d37a2 Mon Sep 17 00:00:00 2001 From: Abdulhaq Emhemmed Date: Mon, 24 Jul 2017 16:44:57 +0200 Subject: [PATCH] Allow for custom instantiation of input serializer --- docs/rest-framework.rst | 26 ++++++++++++++++++++++ graphene_django/rest_framework/mutation.py | 10 +++++++-- 2 files changed, 34 insertions(+), 2 deletions(-) diff --git a/docs/rest-framework.rst b/docs/rest-framework.rst index 5e5dd70..b870af4 100644 --- a/docs/rest-framework.rst +++ b/docs/rest-framework.rst @@ -19,3 +19,29 @@ You can create a Mutation based on a serializer by using the class Meta: serializer_class = MySerializer + +Customizing the mutation +-------- + +By default, when the serializer is instantiated, only the input argument +is passed. Sometimes, the Django `request` object is required in the serializer +context. In fact, any sort of complicated serializer will probably require something +like `request.user`. This can be performed by customizing the instantiation +method as such: + +.. code:: python + + from graphene_django.rest_framework.mutation import SerializerMutation + + class MySecondAwesomeMutation(SerializerMutation): + + @classmethod + def instantiate_serializer(cls, instance, args, request, info): + + input = args.get('input') + + return cls._meta.serializer_class(data=dict(input), + context={'request': request}) + + class Meta: + serializer_class = MySerializer diff --git a/graphene_django/rest_framework/mutation.py b/graphene_django/rest_framework/mutation.py index e5b3be0..2659b8c 100644 --- a/graphene_django/rest_framework/mutation.py +++ b/graphene_django/rest_framework/mutation.py @@ -105,12 +105,18 @@ class SerializerMutation(six.with_metaclass(SerializerMutationMeta, Mutation)): description='May contain more than one error for ' 'same field.' ) + + @classmethod + def instantiate_serializer(cls, instance, args, request, info): + + input = args.get('input') + + return cls._meta.serializer_class(data=dict(input)) @classmethod def mutate(cls, instance, args, request, info): - input = args.get('input') - serializer = cls._meta.serializer_class(data=dict(input)) + serializer = cls.instantiate_serializer(instance, args, request, info) if serializer.is_valid(): return cls.perform_mutate(serializer, info)