gpt4 book ai didi

django - graphql-django 使用可选字段成语更新突变?

转载 作者:行者123 更新时间:2023-12-04 04:18:44 25 4
gpt4 key购买 nike

当使用许多(这里只有 ab)可选的 InputObjectType 字段实现 GraphQL 更新突变时,它会生成大量样板文件来检查 InputObjectTypes 字段是否已传递。是否有一些成语被认为是最佳实践 w.r.t.这个话题?

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

关于django - graphql-django 使用可选字段成语更新突变?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59986354/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com