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

837 views Asked by At

I'm trying to do a graphql query in django. I have a problem with the manuToManu relationship. Can I ask for help? I don't know where I go wrong.

Part written in 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)

Part written in Graphql

query graphql

query {
  pizza{
    name
    toppings {
      name
    }
  }
}

response graphql

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

There are 1 answers

1
JPG On BEST ANSWER

You have to write a custom resolver for toppings in PizzaType class

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()