我正在使用Django-Graphene为我的Web应用程序构建API。我建立了一个简单的结构,其中有Product
的{{1}}:
category
但是当我尝试突变时,我需要传递一个CategoryModel实例,但我不知道该怎么做:
from graphene_django import DjangoObjectType
import graphene
from .models import ProductModel, CategoryModel
class CategoryType(DjangoObjectType):
class Meta:
model = CategoryModel
class ProductType(DjangoObjectType):
category = graphene.Field(CategoryType)
class Meta:
model = ProductModel
class CategoryInput(graphene.InputObjectType):
title = graphene.String()
class ProductInput(graphene.InputObjectType):
title = graphene.String()
category = graphene.Field(CategoryInput)
class Query(graphene.ObjectType):
products = graphene.List(ProductType)
categories = graphene.List(CategoryType)
def resolve_products(self, info):
return ProductModel.objects.all()
def resolve_categories(self, info):
return CategoryModel.objects.all()
class CreateProduct(graphene.Mutation):
class Arguments:
product_data = ProductInput(required=True)
product = graphene.Field(ProductType)
@staticmethod
def mutate(self, info, product_data):
product = ProductModel.objects.create(**product_data)
product.save()
return CreateProduct(product=product)
class CreateCategory(graphene.Mutation):
class Arguments:
title = graphene.String()
category = graphene.Field(CategoryType)
def mutate(self, info, title):
category = CategoryModel(title=title)
category.save()
return CreateCategory(category=category)
class Mutations(graphene.ObjectType):
create_product = CreateProduct.Field()
create_category = CreateCategory.Field()
schema = graphene.Schema(query=Query, mutation=Mutations)
如何创建需要标题和类别的产品?
答案 0 :(得分:-1)
昨天我曾经遇到过类似的问题,但似乎我对GRAPHENE的了解还没有更好。但是我写了一些有趣的代码,它们起作用了,也许会有更多的石墨烯解决方法。
class ProductInput(graphene.InputObjectType):
name = graphene.String()
class ProductPayload(graphene.Mutation):
product = graphene.Field(ProductType)
class Meta:
input = ProductInput(required=True)
category_name = graphene.String(required=True)
def mutate(self, info, input=None, category_name=None):
cat = None
if category_name is not None:
cat = Category.objects.get(name=category_name)
product = Product.objects.create(name=input.name, category=cat)
return ProductPayload(product=product)
class ProductMutation(graphene.ObjectType):
create_product = ProductPayload.Field()
schema = graphene.Schema(mutation=ProductMutation
要在您的Graphiql中进行突变,
mutation {
createProduct(input: {name: "Your product name"}, category_name: "your category name") {
product {
name,
category {
name
}
}
}
}