Django Graphene使用多层嵌套外键编写变异

问题描述

如何编写模式并查询嵌套的外键?我检查了文档,但没有找到如何执行此操作的示例。所以这是我基于github的尝试,而stackoverflow答案可以说我有以下模型:

class Address(models.Model):
    name = models.CharField()

class Person(models.Model):
    name = models.CharField()
    address = models.ForeignKey('Address',on_delete=models.CASCADE,blank=False,null=False)

class Blog(models.Model):
    person = models.ForeignKey('Person',null=False)
    text = models.TextField()

我尝试编写这样的模式:

class AddressInput(graphene.InputObjectType):

    name = graphene.String(required=True)


class PersonInput(graphene.InputObjectType):

    name = graphene.String(required=True)
    address =graphene.Field(AddressInput)

class CreateNewBlog(graphene.Mutation):

    blog=graphene.Field(BlogType)

    class Arguments:
        address_data = AddressInput()
        person_data = PersonInput()
        text = graphene.String()

    @staticmethod
    def mutate(root,info,person_data=None,address_data=None,**input):

        address = Address.objects.create(name=address_data.name)
        person = Person.objects.create(address=address,name=person_data.name)
        blog = Blog.objects.create(person =person,text=input['text'])
        blog.save()

        return CreateNewBlog(blog=blog)

我使用了这样的查询:

mutation {
        CreateNewBlog(person: { address: {name: "aaa"},name: "First Last" },text: "hi hi") {
            Blog {
              person{
                name
                address{
                  name
                }
              },text
                
            }
        }
}

我收到此错误消息:

{
  "errors": [
    {
      "message": "'NoneType' object has no attribute 'name'","locations": [
        {
          "line": 32,"column": 9
        }
      ],"path": [
        "CreateNewBlog"
      ]
    }
  ],"data": {
    "CreateNewBlog": null
  }
}

我认为问题出在我编写schema.py文件的方式中。无法将InputField嵌套在另一个InputField中的地方。还有其他写单个突变的方法吗?

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)