a
当使用许多(这里只是和)可选的 InputObjectType 字段实现 GraphQL 更新突变时,b
它会生成大量样板文件来检查 InputObjectTypes 字段是否已通过。是否有一些成语被认为是这个主题的最佳实践?
# <app>/models.py
from django.db import models
class Something(models.Model):
a = models.CharField(default='')
b = models.CharField(default='')
# <app>/schema.py
import graphene
from graphene_django import DjangoObjectType
from .models import Something
class SomethingType(DjangoObjectType):
class Meta:
model = Something
class SomethingInput(graphene.InputObjectType):
# all fields are optional
a = graphene.String()
b = graphene.String()
class SomethingUpdateMutation(graphene.Mutation):
class Arguments:
id = graphene.ID(required=True)
something_data = SomethingInput(required=True)
something = graphene.Field(SomethingType)
def mutate(self, info, id, something_data):
something_db = Something.objects.get(pk=id)
# checking if fields have been passed or not and
# only change corresponding db value if value has been passed
if something_data.a is not None:
something_db.a = something_data.a
if something_data.b is not None:
something_db.b = something_data.b
something_db.save()
return SomethingUpdateMutation(something=something)
class Mutation(object):
# project schema inherits from this class
something_update_mutation = SomethingUpdateMutation.Field()