ошибка мутации, Неизвестный аргумент \ штрих-код \ в поле \ createProduct \ типа \ Mutation \ - django

Я делаю обучающие материалы в Интернете и пытаюсь заставить mutation работать на graphql, но я продолжал получать ошибки, из-за которых я понятия не имел, откуда взялась настоящая ошибка и как начать отладку там, где я сделал неправильно.

ищу на YouTube мутации https://www.youtube.com/watch?v=aB6c7UUMrPo&t=1962s и документация по графену http://docs.graphene-python.org/en/latest/types/mutations/

Я заметил, что из-за другой версии графена, поэтому я читаю документацию, а не следую в точности как youtube

Я получил все настройки, но потом не смог заставить его работать, когда я выполняю запрос на мутацию, я получаю ошибку.

У меня есть такая модель.

class Product(models.Model):
    sku = models.CharField(max_length=13, help_text="Enter Product Stock Keeping Unit", null=True, blank=True)
    barcode = models.CharField(max_length=13, help_text="Enter Product Barcode (ISBN, UPC ...)", null=True, blank=True)

    title = models.CharField(max_length=200, help_text="Enter Product Title", null=True, blank=True)
    description = models.TextField(help_text="Enter Product Description", null=True, blank=True)

    unitCost = models.FloatField(help_text="Enter Product Unit Cost", null=True, blank=True)
    unit = models.CharField(max_length=10, help_text="Enter Product Unit ", null=True, blank=True)

    quantity = models.FloatField(help_text="Enter Product Quantity", null=True, blank=True)
    minQuantity = models.FloatField(help_text="Enter Product Min Quantity", null=True, blank=True)

    family = models.ForeignKey('Family', null=True, blank=True)
    location = models.ForeignKey('Location', null=True, blank=True)

    def __str__(self):
        return self.title

У меня есть это для моего продукта schema

class ProductType(DjangoObjectType):
    class Meta:
        model = Product
        filter_fields = {'description': ['icontains']}
        interfaces = (graphene.relay.Node,)


class CreateProduct(graphene.Mutation):
    class Argument:
        barcode = graphene.String()

    # form_errors = graphene.String()
    product = graphene.Field(lambda: ProductType)

    def mutate(self, info, barcode):
        product = Product(barcode=barcode)
        return CreateProduct(product=product)


class ProductMutation(graphene.AbstractType):
    create_product = CreateProduct.Field()

class ProductQuery(object):
    product = relay.Node.Field(ProductType)
    all_products = DjangoFilterConnectionField(ProductType)

    def resolve_all_products(self, info, **kwargs):
        return Product.objects.all()

глобальная схема выглядит так

class Mutation(ProductMutation,
               graphene.ObjectType):
    pass


class Query(FamilyQuery,
            LocationQuery,
            ProductQuery,
            TransactionQuery,

            graphene.ObjectType):
    # This class extends all abstract apps level Queries and graphene.ObjectType
    pass


allGraphQLSchema = graphene.Schema(query=Query, mutation=Mutation)

что касается проверки запросов ... это мой запрос

mutation ProductMutation {
  createProduct(barcode:"abc"){
    product {
      id, unit, description
    }
  }
}

ошибка вернулась

{
  "errors": [
    {
      "message": "Unknown argument \"barcode\" on field \"createProduct\" of type \"Mutation\".",
      "locations": [
        {
          "column": 17,
          "line": 2
        }
      ]
    }
  ]
}

Может ли кто-нибудь помочь мне в том, что я должен попробовать и сделать?

Заранее благодарю за любую помощь


person Dora    schedule 01.12.2017    source источник


Ответы (1)


Прикинул свою проблему.

Есть три вещи, которые Argument должны быть Arguments, а под функцией mutate я должен использовать обычную модель создания django, поэтому от product = Product(barcode=barcode) до product = Product.objects.create(barcode=barcode) последнее, но не менее class ProductMutation(graphene.AbstractType): должно быть class ProductMutation(graphene.ObjectType):

поэтому код должен быть

class ProductType(DjangoObjectType):
    class Meta:
        model = Product
        filter_fields = {'description': ['icontains']}
        interfaces = (graphene.relay.Node,)


class CreateProduct(graphene.Mutation):
    class Arguments:    # change here
        barcode = graphene.String()

    product = graphene.Field(lambda: ProductType)

    def mutate(self, info, barcode):
        # change here
        # somehow the graphene documentation just state the code I had in my question which doesn't work for me.  But this one does
        product = Product.objects.create(barcode=barcode)
        return CreateProduct(product=product)


class ProductMutation(graphene.ObjectType):  # change here
    create_product = CreateProduct.Field()

class ProductQuery(object):
    product = relay.Node.Field(ProductType)
    all_products = DjangoFilterConnectionField(ProductType)

    def resolve_all_products(self, info, **kwargs):
        return Product.objects.all()
person Dora    schedule 02.12.2017