如何在石墨烯方案中使用多个关系?

2024-09-28 19:01:59 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试用django进行graphql查询。我对manuToManu的关系有问题。我能寻求帮助吗?我不知道我哪里出错了

用Python编写的部分

models.py

class Topping(models.Model):
    id = models.AutoField(primary_key=True)
    name = models.CharField(max_length=50)

    def __str__(self):
        return self.name

class Pizza(models.Model):
    id = models.AutoField(primary_key=True)
    name = models.CharField(max_length=50)
    toppings = models.ManyToManyField(Topping)

schema.py

class Query(graphene.ObjectType):
    pizza = graphene.List(PizzaType)
    topping = graphene.List(ToppingType)

    @staticmethod
    def resolve_pizza(parent, info):
        return Pizza.objects.all()

    @staticmethod
    def resolve_topping(parent, info):
        return Topping.objects.all()

types.py

class ToppingType(graphene.ObjectType):
    id = graphene.NonNull(graphene.Int)
    name = graphene.NonNull(graphene.String)

class PizzaType(graphene.ObjectType):
    id = graphene.NonNull(graphene.Int)
    name = graphene.NonNull(graphene.String)
    toppings = graphene.List(ToppingType)

用图形ql编写的零件

查询图ql

query {
  pizza{
    name
    toppings {
      name
    }
  }
}

响应图ql

{
  "errors": [
    {
      "message": "User Error: expected iterable, but did not find one for field PizzaType.toppings."
    }
  ],
  "data": {
    "pizza": [
      {
        "name": "mafia",
        "toppings": null
      }
    ]
  }
}

Tags: namepyidreturnmodelsdeflistclass
1条回答
网友
1楼 · 发布于 2024-09-28 19:01:59

您必须在PizzaType类中为toppings编写自定义解析器

class PizzaType(graphene.ObjectType):
    id = graphene.NonNull(graphene.Int)
    name = graphene.NonNull(graphene.String)
    toppings = graphene.List(ToppingType)

    @staticmethod
    def resolve_toppings(pizza, *args, **kwargs):
        return pizza.toppings.all()

相关问题 更多 >