【问题标题】:Django/Graphene Mutation error "you need to pass a valid Django model" can't fix it [duplicate]Django / Graphene Mutation错误“你需要传递一个有效的Django模型”无法修复它[重复]
【发布时间】:2020-08-08 17:36:23
【问题描述】:

下面是我正在使用的 Django/Graphene 示例的 RDBMS 图:

以下是我的应用程序的 model.py 代码:

from django.db import models

# Create your models here.
class ProductCategory(models.Model):
  category = models.CharField(max_length=50)
  parentCategory = models.ForeignKey('self',null=True, on_delete=models.CASCADE)

class Product(models.Model):
  productNumber= models.CharField(max_length=50)
  description = models.CharField(max_length=50)
  productCategory= models.ForeignKey('product.ProductCategory', on_delete=models.PROTECT)

下面是应用程序的 Schema.py:

import graphene
from graphene_django import DjangoObjectType

from .models import Product, ProductCategory

class ProductType(DjangoObjectType):
  class Meta:
    model = Product

class ProductCategoryType(DjangoObjectType):
  class Meta:
    model = ProductCategory

class Query(graphene.ObjectType):
  products = graphene.List(ProductType)
  productCategories = graphene.List(ProductCategoryType)

  def resolve_products(self, info):
      return Product.objects.all()
  def resolve_productCategories(self,info):
      return ProductCategory.objects.all()


class CreateProductCategory(DjangoObjectType):
  productCategory = graphene.Field(ProductCategoryType)

  class Arguments:
    category = graphene.String(required=True)
    parentCategory = graphene.Int()
  
  def mutate(self, info, category, parentCategory):
    productCategory = ProductCategory(category = category, parentCategory = parentCategory)
    productCategory.save()
    return CreateProductCategory(productCategory=productCategory)

    return CreateProductCategory(category=category,parentCategory=parentCategory)

class Mutation(graphene.ObjectType):
  createProductCategory= CreateProductCategory.Field()

没有变异代码,查询请求可以正常工作,如下图所示

但是当添加突变代码时它会输出一个错误,我无法弄清楚我做错了什么,因为我是一个菜鸟。请帮忙!!

AssertionError: You need to pass a valid Django Model in CreateProductCategory.Meta, received "None".

【问题讨论】:

标签: django graphene-django


【解决方案1】:

这是问题所在:class CreateProductCategory(DjangoObjectType)

你需要继承graphene.Mutation,而不是DjangoObjectType,才能进行突变。

正确:class CreateProductCategory(graphene.Mutation) `

【讨论】:

  • 谢谢!它就像一个魅力。
猜你喜欢
  • 2019-03-22
  • 1970-01-01
  • 2020-01-18
  • 2018-12-15
  • 1970-01-01
  • 2020-09-12
  • 2021-08-22
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多