2017-02-14 21:23:45 +03:00
|
|
|
import graphene
|
|
|
|
from graphene_django.types import DjangoObjectType
|
|
|
|
|
2018-10-18 21:33:53 +03:00
|
|
|
from .models import Category, Ingredient
|
2017-02-14 21:23:45 +03:00
|
|
|
|
|
|
|
|
|
|
|
class CategoryType(DjangoObjectType):
|
|
|
|
class Meta:
|
|
|
|
model = Category
|
|
|
|
|
|
|
|
|
|
|
|
class IngredientType(DjangoObjectType):
|
|
|
|
class Meta:
|
|
|
|
model = Ingredient
|
|
|
|
|
|
|
|
|
2018-06-05 22:53:47 +03:00
|
|
|
class Query(object):
|
2017-02-14 21:23:45 +03:00
|
|
|
category = graphene.Field(CategoryType,
|
|
|
|
id=graphene.Int(),
|
|
|
|
name=graphene.String())
|
|
|
|
all_categories = graphene.List(CategoryType)
|
|
|
|
|
|
|
|
ingredient = graphene.Field(IngredientType,
|
|
|
|
id=graphene.Int(),
|
|
|
|
name=graphene.String())
|
|
|
|
all_ingredients = graphene.List(IngredientType)
|
|
|
|
|
2018-10-18 22:27:23 +03:00
|
|
|
def resolve_all_categories(self, context):
|
2017-02-14 21:23:45 +03:00
|
|
|
return Category.objects.all()
|
|
|
|
|
2018-10-18 22:27:23 +03:00
|
|
|
def resolve_all_ingredients(self, context):
|
2017-02-14 21:23:45 +03:00
|
|
|
# We can easily optimize query count in the resolve method
|
|
|
|
return Ingredient.objects.select_related('category').all()
|
|
|
|
|
2018-10-18 22:27:23 +03:00
|
|
|
def resolve_category(self, context, id=None, name=None):
|
2017-02-14 21:23:45 +03:00
|
|
|
if id is not None:
|
|
|
|
return Category.objects.get(pk=id)
|
|
|
|
|
|
|
|
if name is not None:
|
|
|
|
return Category.objects.get(name=name)
|
|
|
|
|
|
|
|
return None
|
|
|
|
|
2018-10-18 22:27:23 +03:00
|
|
|
def resolve_ingredient(self, context, id=None, name=None):
|
2017-02-14 21:23:45 +03:00
|
|
|
if id is not None:
|
|
|
|
return Ingredient.objects.get(pk=id)
|
|
|
|
|
|
|
|
if name is not None:
|
|
|
|
return Ingredient.objects.get(name=name)
|
|
|
|
|
|
|
|
return None
|