mirror of
				https://github.com/graphql-python/graphene-django.git
				synced 2025-10-30 23:47:30 +03:00 
			
		
		
		
	Allow for custom instantiation of input serializer
This commit is contained in:
		
							parent
							
								
									cec1a84480
								
							
						
					
					
						commit
						412747d632
					
				|  | @ -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 | ||||
|  |  | |||
|  | @ -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) | ||||
|  |  | |||
		Loading…
	
		Reference in New Issue
	
	Block a user