当实现GraphQL更新突变时,会有很多(这里仅指 a
和 b
)可选的InputObjectType字段,它产生了大量的模板来检查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()
你可以这样做。
def mutate(self, info, **kwargs):
user = info.context.user
for k, v in kwargs.items():
user.k = v
user.save()
return UpdateUser(user=user)
但我还是在找一些优雅的方法来做。🤘
但是,如果用户想从字段中删除内容,那么你会怎么做,因为你是在检查 !None
. 我认为,最好的做法是,当我们更新一个数据时,我们发送所有数据与更新的字段。因此,我们不需要检查,是空的东西或没有。