【问题标题】:How do I use the manyToMany relationship in a graphene scheme?如何在石墨烯方案中使用多对多关系?
【发布时间】:2021-01-19 09:38:56
【问题描述】:

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

响应 graphql

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

【问题讨论】:

    标签: python django graphql graphene-django


    【解决方案1】:

    您必须在 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()

    【讨论】:

    • 非常感谢您的好回答。我试图做这样的事情,但没有在方法中提供这样的参数
    猜你喜欢
    • 2019-03-31
    • 2019-05-03
    • 2018-09-19
    • 2018-09-04
    • 2020-07-27
    • 2019-12-20
    • 2022-01-17
    • 2017-05-13
    • 2018-07-10
    相关资源
    最近更新 更多