【问题标题】:How to get Django Graphene ModelForm Mutation to apply如何让 Django Graphene ModelForm Mutation 应用
【发布时间】:2020-09-12 23:36:30
【问题描述】:

我正试图让这个突变在数据库中创建一条新记录。它返回代码 200 但对数据库没有任何更改,而且它返回 null。 文档对此问题并不清楚。(ModelForm vs mutate function)

Graphql 响应:

{
  "data": {
    "addSubjectMark": {
      "subjectMark": null,
      "errors": []
    }
  }
}

根据 django-graphene 文档,我使用 DjangoModelForm 来处理数据库的输入。

我的 schema.py:

class SubjectMarkType(DjangoObjectType):
    id = graphene.ID(required=True)
    class Meta:
        model = SubjectMark

class AddSubjectMarkMutation(DjangoModelFormMutation):
    subject_mark = graphene.Field(SubjectMarkType)
    class Meta:
        form_class = ReportForm

class Mutation(graphene.ObjectType):
    add_subject_mark = AddSubjectMarkMutation.Field()
  1. 我需要在表单中添加保存方法吗?
  2. 我需要使用mutate函数吗?(文档不清楚)

谢谢!

【问题讨论】:

    标签: django graphene-django graphql-python


    【解决方案1】:

    ReportForm 应该默认使用 Django,不需要修改。 缺少的部分是解析AddSubjectMarkMutation 类中的subject_mark 属性。

    class SubjectMarkType(DjangoObjectType):
        id = graphene.ID(required=True)
    
        class Meta:
            model = SubjectMark
    
    
    class AddSubjectMarkMutation(DjangoModelFormMutation):
        subject_mark = graphene.Field(SubjectMarkType)
    
        class Meta:
            form_class = ReportForm  # NB. make sure ReportForm is able to save in Django
    
        # you need to resolve subject_mark to return the new object
        def resolve_subject_mark(self, info, **kwargs):
            return self.subjectMark
    
    
    class Mutation(graphene.ObjectType):
        add_subject_mark = AddSubjectMarkMutation.Field()
    

    【讨论】:

      猜你喜欢
      • 2019-03-22
      • 2018-12-15
      • 2012-10-24
      • 2017-03-15
      • 2017-12-03
      • 2017-03-21
      • 2021-02-07
      • 2018-03-31
      • 2019-09-22
      相关资源
      最近更新 更多