我是 graphql 的新手,我发现在 django-graphql 中使用来自两个不同应用程序的模式有困难?
Posted
技术标签:
【中文标题】我是 graphql 的新手,我发现在 django-graphql 中使用来自两个不同应用程序的模式有困难?【英文标题】:I am new to graphql and I am finding difficulty in using schema from two different apps in django-graphql? 【发布时间】:2020-10-08 11:42:02 【问题描述】:我是 graphql 的新手,我发现在 django-graphql 中使用来自两个不同应用程序的架构有困难?
app1 hero schema.py
import graphene
from graphene_django import DjangoObjectType
from .models import Hero
class HeroType(DjangoObjectType):
class Meta:
model = Hero
class Query(graphene.ObjectType):
heroes = graphene.List(HeroType)
def resolve_heroes(self, info, **kwargs):
return Hero.objects.all()
app2 产品架构.py
class ProductType(DjangoObjectType):
class Meta:
model = Product
class Query(object):
allproducts = graphene.List(ProductType, search=graphene.String(),limit=graphene.Int(),skip=graphene.Int(), offset=graphene.Int())
def resolve_allproducts(self, info, search=None, limit=None, skip=None, offset=None, **kwargs):
# Querying a list of products
qs = Product.objects.all()
data = []
if search:
filter = (
Q(name__icontains=search)|
Q(price__icontains=search)
)
qs = qs.filter(filter)
if skip:
qs = qs[skip:]
if limit:
# qs = qs[:limit]
qs = qs[int(offset):(int(offset) + int(limit))]
return qs
我的问题: 在主项目schema.py中,如何从app1-hero和app2-product调用schema?
【问题讨论】:
【参考方案1】:您可以将两个查询导入为不同的名称。您的主 schema.py 看起来像这样:
import graphene
from app1.schema import Query as app1_query
from app2.schema import Query as app2_query
class Query(app1_query, app2_query):
# This class will inherit from multiple Queries
pass
schema = graphene.Schema(query=Query)
【讨论】:
【参考方案2】:只需在您的应用中定义类型(比如说在 query.py
文件中)及其解析器。
import graphene
from graphene_django import DjangoObjectType
from .models import Hero
class HeroType(DjangoObjectType):
class Meta:
model = Hero
def resolve_hero_type(info):
# your resolver
然后在schema.py
from app1.query import ProductType, resolve_product_type
from app2.query import HeroType, resolve_hero_type
class Query(object):
all_products = graphene.List(ProductType, search=graphene.String(), limit=graphene.Int(),skip=graphene.Int(), offset=graphene.Int())
heroes = graphene.List(HeroType)
def resolve_all_products(self, info):
return resolve_product_type(info)
def resolve_heroes(self, info):
return resolve_hero_type(info)
【讨论】:
谢谢车切。这对我有用..我被困了很长时间......你帮我解决了这个问题。再次感谢您。以上是关于我是 graphql 的新手,我发现在 django-graphql 中使用来自两个不同应用程序的模式有困难?的主要内容,如果未能解决你的问题,请参考以下文章