diff --git a/recipes/models.py b/recipes/models.py index c610cec..781f751 100644 --- a/recipes/models.py +++ b/recipes/models.py @@ -1,11 +1,12 @@ from django.conf import settings -from django.db.models import (Model, CharField, ForeignKey, IntegerField, +from django.db.models import (Model, AutoField, CharField, ForeignKey, IntegerField, TextField, DecimalField, ManyToManyField, CASCADE) from inventory.models import QuantitativeUnit, Product class Recipe(Model): + id = AutoField(primary_key=True) instructions = TextField(blank=True) ingredients = ManyToManyField(Product, through='Ingredient') name = CharField(max_length=255) diff --git a/recipes/schema.py b/recipes/schema.py index 3b7eef3..28e8ffa 100644 --- a/recipes/schema.py +++ b/recipes/schema.py @@ -3,11 +3,13 @@ from graphene_django import DjangoObjectType from graphene_django.filter import DjangoFilterConnectionField from .models import Recipe, Ingredient +from django.core.exceptions import ObjectDoesNotExist class IngredientType(DjangoObjectType): class Meta: model = Ingredient + fields = "__all__" class RecipeType(DjangoObjectType): @@ -16,29 +18,32 @@ class Meta: fields = "__all__" filter_fields = {'name': ['icontains'], 'ingredient__product__id': ['exact']} interfaces = (Node, ) - interfaces = (graphene.Node,) + + recipe_id = graphene.ID() + + def resolve_recipe_id(self, info): + return self.id class Query(graphene.ObjectType): - recipe = graphene.Field(RecipeType, id=graphene.Int(), + recipe = graphene.Field(RecipeType, id=graphene.ID(required=True), name=graphene.String()) recipes = DjangoFilterConnectionField(RecipeType) class Arguments: - ingredient_id = graphene.ID() - - def resolve_recipe(self, info, **kwargs): - id = kwargs.get('id') - name = kwargs.get('name') + ingredient_id = graphene.ID(required=True) - if id is not None: - return Recipe.objects.get(pk=id) + def resolve_recipe(self, info, id: graphene.ID = None, name: str = None): + try: + if id: + return Recipe.objects.get(pk=id) - if name is not None: - return Recipe.objects.get(name=name) + if name: + return Recipe.objects.get(name=name) - return None + except ObjectDoesNotExist: + return None def resolve_recipes(self, info, **kwargs): return Recipe.objects.all()