Skip to content

Instantly share code, notes, and snippets.

@mbrochh
Created May 4, 2016 04:47
Show Gist options
  • Save mbrochh/9a90d24ca9d0a78e3c1d642aea0663b7 to your computer and use it in GitHub Desktop.
Save mbrochh/9a90d24ca9d0a78e3c1d642aea0663b7 to your computer and use it in GitHub Desktop.
GraphQL Schema
query {
products {
id
}
}
{
"errors": [
{
"message": "Product received a non-compatible instance (QuerySet) when expecting Product",
"locations": [
{
"column": 5,
"line": 3
}
]
}
],
"data": {
"products": null
}
}
import graphene
from graphene import relay, resolve_only_args
from graphene.contrib.django.types import DjangoNode
from . import models
class Product(DjangoNode):
class Meta:
model = models.Product
@classmethod
def get_node(cls, id, info):
return Product(models.Product.objects.get(pk=id))
class Query(graphene.ObjectType):
node = relay.NodeField()
products = graphene.Field(Product)
@resolve_only_args
def resolve_products(self):
return models.Product.objects.all()
schema = graphene.Schema(name='Luxglove Schema')
schema.query = Query
@syrusakbary
Copy link

syrusakbary commented May 4, 2016

Try with graphene.List(Product) instead of graphene.Field(Product), as Field only expects one item (or None) instead of a iterator.

class Query(graphene.ObjectType):
    node = relay.NodeField()
    products = graphene.List(Product)

    @resolve_only_args
    def resolve_products(self):
        return models.Product.objects.all()

@mbrochh
Copy link
Author

mbrochh commented May 4, 2016

@syrusakbary that was helpful! Thank you!

Now I'm facing another issue. This query:

{
  products(id: 100) {
    title
  }
}

Gives this error:

{
  "errors": [
    {
      "message": "Unknown argument \"id\" on field \"products\" of type \"Query\".",
      "locations": [
        {
          "column": 12,
          "line": 2
        }
      ]
    }
  ]
}

Any idea why?

@syrusakbary
Copy link

For having an argument in a Field (in this case the products field in the Query type), you need to specify when creating the field. Like:

class Query(graphene.ObjectType):
    node = relay.NodeField()
    products = graphene.List(Product, id=graphene.String())

    @resolve_only_args
    def resolve_products(self, id=None):
        return models.Product.objects.filter(id=id)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment