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
|
2020-06-11 13:09:52 +03:00
|
|
|
fields = "__all__"
|
2017-02-14 21:23:45 +03:00
|
|
|
|
|
|
|
|
|
|
|
class IngredientType(DjangoObjectType):
|
|
|
|
class Meta:
|
|
|
|
model = Ingredient
|
2020-06-11 13:09:52 +03:00
|
|
|
fields = "__all__"
|
2017-02-14 21:23:45 +03:00
|
|
|
|
|
|
|
|
2022-10-19 17:10:30 +03:00
|
|
|
class Query:
|
2019-06-11 06:54:30 +03:00
|
|
|
category = graphene.Field(CategoryType, id=graphene.Int(), name=graphene.String())
|
2017-02-14 21:23:45 +03:00
|
|
|
all_categories = graphene.List(CategoryType)
|
|
|
|
|
2019-06-11 06:54:30 +03:00
|
|
|
ingredient = graphene.Field(
|
|
|
|
IngredientType, id=graphene.Int(), name=graphene.String()
|
|
|
|
)
|
2017-02-14 21:23:45 +03:00
|
|
|
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
|
2019-06-11 06:54:30 +03:00
|
|
|
return Ingredient.objects.select_related("category").all()
|
2017-02-14 21:23:45 +03:00
|
|
|
|
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
|