简体   繁体   English

如何获得Django Graphene ModelForm Mutation来申请

[英]How to get Django Graphene ModelForm Mutation to apply

I'm trying to make this mutation create a new record in the database.我试图让这个突变在数据库中创建一个新记录。 It returns code 200 but no change to the database plus it returns null.它返回代码 200 但对数据库没有任何更改,而且它返回 null。 The documentation is not clear on this issue.(ModelForm vs mutate function)该问题的文档尚不清楚。(ModelForm vs mutate function)

Graphql response: Graphql 响应:

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

According to django-graphene documentation, I'm using DjangoModelForm to handle the input into the db.根据 django-graphene 文档,我使用 DjangoModelForm 处理输入到数据库中。

My schema.py:我的 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. Do I need to add a save method to the form?我需要在表单中添加保存方法吗?
  2. Do I need to use the mutate function?(Docs unclear)我需要使用变异 function 吗?(文档不清楚)

Thanks!谢谢!

The ReportForm should work as default with Django no modification is required. ReportForm应默认与 Django 一起使用,无需修改。 The missing piece is resolving the subject_mark attribute in the AddSubjectMarkMutation class.缺少的部分是解析AddSubjectMarkMutation class 中的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()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM