2

我是graphql的新手,我发现在 django-graphql 中使用来自两个不同应用程序的模式有困难?

app1 英雄 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 产品 schema.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 调用架构?

4

2 回答 2

2

您可以将两个查询作为不同的名称导入。您的主要 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)
于 2020-07-26T10:45:25.060 回答
0

只需使用它们的解析器在您的应用程序中定义类型(比如说在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)
于 2020-07-08T21:38:34.050 回答