2

I am new to graphql and I am finding difficulty in using schema from two different apps in 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 product 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

My problem:
In main project schema.py, how do I call schema from app1-hero and app2-product?

Houda
  • 671
  • 6
  • 16

2 Answers2

2

You can import both Queries as different names. Your main schema.py would look like this:

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)
Dharman
  • 30,962
  • 25
  • 85
  • 135
Booshra
  • 63
  • 7
0

Just define types in your apps (lets say inside a query.py file) with their resolvers.

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

And then in 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)
Cheche
  • 1,456
  • 10
  • 27