1

变异函数在执行更新操作时需要很多参数。根据官方石墨烯文档,我可以使用 ( parent , root , obj ) 对象来访问我的类对象。

我尝试使用 parent、root 和 obj 来访问可变数据,但没有成功。

class UpdateEvent(graphene.Mutation):
    ok = graphene.Boolean()

    class Arguments:
        id = graphene.ID()
        name = graphene.String()

        event_start_date = graphene.types.datetime.Date()
        event_finish_date = graphene.types.datetime.Date()

        event_mark_as_finished = graphene.Boolean()

        event_description = graphene.String()

        event_location = graphene.String()

        event_price = graphene.Float()
        event_price_unit = graphene.String()


    def mutate(root, info):

       event = Events.objects.get(pk=root.id)
       event.name = root.name  
       event.event_start_date = root.event_start_date 
       event.event_finish_date= root.event_finish_date
       event.event_mark_as_finished = root.event_mark_as_finished
       event.event_description = root.event_description
       event.event_location = root.event_location
       event.event_price = root.event_price
       event.event_price_unit = root.event_price_unit
       event.save()


       # This class registered to the Mutation class*** 

"errors": [{ "message": "mutate() got an unexpected keyword argument 'event_description'"}]

将所有变量放入 mutate 函数中效果很好,但这是一种丑陋的方式。我该如何处理?

4

1 回答 1

1

用单一输入类型包装它们:

class UpdateEventMutationInput(graphene.InputObjectType):
    id = graphene.ID()
    name = graphene.String()

    event_start_date = graphene.types.datetime.Date()
    event_finish_date = graphene.types.datetime.Date()
    event_mark_as_finished = graphene.Boolean()
    event_description = graphene.String()
    event_location = graphene.String()
    event_price = graphene.Float()
    event_price_unit = graphene.String()

并在突变中使用它:

class UpdateEvent(graphene.Mutation):
    ok = graphene.Boolean()

    class Arguments:
        data = UpdateEventMutationInput(required=True)

    def mutate(root, info, data):
       event = Events.objects.get(pk=data.id)
       event.name = data.name  
       event.event_start_date = data.event_start_date 
       event.event_finish_date= data.event_finish_date
       event.event_mark_as_finished = data.event_mark_as_finished
       event.event_description = data.event_description
       event.event_location = data.event_location
       event.event_price = data.event_price
       event.event_price_unit = data.event_price_unit
       event.save()

它还带来了这样的优势:

  1. 更少的突变代码
  2. 为这个突变写一个请求很容易(它将包含一个$data: UpdateEventMutationInput!变量)
  3. 更少的跨版本冲突,因为您不必在突变输入更改时更新请求
于 2019-07-25T16:39:50.450 回答