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

How do I use the manyToMany relationship in a graphene scheme?

我正在尝试在 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)

部分用 Graphql 编写

查询graphql

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
      }
    ]
  }
}

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

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

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