mirror of
https://github.com/graphql-python/graphene-django.git
synced 2025-02-16 19:40:36 +03:00
Allow upserts when converting DRF serializers
Combine create and update into a single mutation. This can be disabled by returning None from `load_existing`.
This commit is contained in:
parent
9ef31d849d
commit
0b5f8e8507
|
@ -1,16 +1,12 @@
|
||||||
from collections import OrderedDict
|
from collections import OrderedDict
|
||||||
|
|
||||||
import graphene
|
import graphene
|
||||||
|
from graphene.relay.mutation import ClientIDMutation
|
||||||
from graphene.types import Field, InputField
|
from graphene.types import Field, InputField
|
||||||
from graphene.types.mutation import MutationOptions
|
from graphene.types.mutation import MutationOptions
|
||||||
from graphene.relay.mutation import ClientIDMutation
|
from graphene.types.objecttype import yank_fields_from_attrs
|
||||||
from graphene.types.objecttype import (
|
|
||||||
yank_fields_from_attrs
|
|
||||||
)
|
|
||||||
|
|
||||||
from .serializer_converter import (
|
from .serializer_converter import convert_serializer_field
|
||||||
convert_serializer_field
|
|
||||||
)
|
|
||||||
from .types import ErrorType
|
from .types import ErrorType
|
||||||
|
|
||||||
|
|
||||||
|
@ -69,7 +65,8 @@ class SerializerMutation(ClientIDMutation):
|
||||||
|
|
||||||
@classmethod
|
@classmethod
|
||||||
def mutate_and_get_payload(cls, root, info, **input):
|
def mutate_and_get_payload(cls, root, info, **input):
|
||||||
serializer = cls._meta.serializer_class(data=input)
|
existing = cls.load_existing(cls._meta.serializer_class, input)
|
||||||
|
serializer = cls._meta.serializer_class(existing, data=input)
|
||||||
|
|
||||||
if serializer.is_valid():
|
if serializer.is_valid():
|
||||||
return cls.perform_mutate(serializer, info)
|
return cls.perform_mutate(serializer, info)
|
||||||
|
@ -81,7 +78,15 @@ class SerializerMutation(ClientIDMutation):
|
||||||
|
|
||||||
return cls(errors=errors)
|
return cls(errors=errors)
|
||||||
|
|
||||||
|
@classmethod
|
||||||
|
def load_existing(cls, serializer_class, data):
|
||||||
|
id = data.get('id')
|
||||||
|
if id is not None:
|
||||||
|
model_class = serializer_class.Meta.model
|
||||||
|
return model_class.objects.get(id=data['id'])
|
||||||
|
return None
|
||||||
|
|
||||||
@classmethod
|
@classmethod
|
||||||
def perform_mutate(cls, serializer, info):
|
def perform_mutate(cls, serializer, info):
|
||||||
obj = serializer.save()
|
serializer.save()
|
||||||
return cls(errors=None, **obj)
|
return cls(errors=None, **serializer.data)
|
||||||
|
|
Loading…
Reference in New Issue
Block a user