3

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()
4

1 回答 1

1

你可以这样做:

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. IMO,最佳实践,当我们更新数据时,我们会发送所有带有更新字段的数据。所以我们不需要检查,是不是空的。

于 2020-04-22T18:56:36.687 回答