def setRecipeIngredients(request, recipe): """ Saves the current ingredients and quantity for Recipe. """ quantity_str = "quantity" ingredient_str = "ingredient" for x in range(1, 12): try: i= request.POST.get(ingredient_str + str(x)) quantity = request.POST.get(quantity_str + str(x)) if quantity and i: ri = Recipeingredients() existingIngredient = None existingIngredient = Ingredient.objects.filter(name=i) if not len(existingIngredient) == 0 : for ingredient in existingIngredient: ri.ingredient = ingredient ri.recipe = recipe ri.quantity = quantity ri.save() else: ingredient = Ingredient() ingredient.name = i ingredient.save() ri.ingredient = ingredient ri.recipe = recipe ri.quantity = quantity ri.save() except: return
class RecipeModelTest(TestCase): def setUp(self): self.lasanha = Recipe(title='lasanha', description='placeholder') self.macarrao = Recipe(title='macarrao', description='placeholder') self.batata = Ingredient(name='batata') self.molho = Ingredient(name='molho') def test_recipe_is_saved(self): self.lasanha.save() self.macarrao.save() self.assertEqual('lasanha', Recipe.objects.all()[0].title) def test_update_ingredients_method(self): self.lasanha.save() self.batata.save() self.molho.save() Measure.objects.create(recipe=self.lasanha, ingredient=self.batata, measure='duas') new_ingredients = {'batata': 'uma', 'molho': 'um'} new_ingredients2 = {'cenoura': 'uma'} self.lasanha.update_ingredients(new_ingredients) self.assertEqual(self.lasanha.measure_set.all().count(), 2) self.assertEqual( self.lasanha.measure_set.get(ingredient=self.batata).measure, 'uma') self.assertEqual( self.lasanha.measure_set.get(ingredient=Ingredient.objects.get( name='molho')).measure, 'um') self.lasanha.update_ingredients(new_ingredients2) self.assertEqual(self.lasanha.ingredients.count(), 1) self.assertEqual( self.lasanha.measure_set.get(ingredient=Ingredient.objects.get( name='cenoura')).measure, 'uma')
def handle_ingredient(self, recipe, name, amount, ingredientid, grams): self.stdout.write(u"\t - ingredient: %s | %s" % (amount, name)) # Look for food ingredient = Ingredient.objects.search(name) if not ingredient: if self.create_foods: ingredient = Ingredient() ingredient.NDB_No = self.ingredient_NDB_No_generator() ingredient.Shrt_Desc = name ingredient.Long_Desc = name ingredient.save() else: raise Exception("Ingredient failed!") ing_amount = IngredientWithAmount(Recipe=recipe, Ingredient=ingredient) ing_amount.HumanReadable = u"%s %s" % (amount, name) ing_amount.GramsEquiv = grams # Quantity and Units items = amount.split() try: ing_amount.Quantity = float( sum(Fraction(part) for part in items[0].split())) if len(items) == 1: ing_amount.Units = u"unit" else: ing_amount.Units = items[-1] self.stdout.write(u"\t + ingredient: %s" % (ingredient.Shrt_Desc)) self.stdout.write(u"\t + quantity: %s" % (ing_amount.Quantity)) self.stdout.write(u"\t + units: %s" % (ing_amount.Units)) ing_amount.save() except Exception as e: self.stderr.write(str(e)) ingredient.delete() raise Exception("Quanty and units not parseable: %r" % amount)
class MeasureRelationTest(TestCase): def setUp(self): self.lasanha = Recipe(title='lasanha', description='placeholder') self.batata = Ingredient(name='batata') def test_create_association(self): self.lasanha.save() self.batata.save() Measure(ingredient=self.batata, recipe=self.lasanha, measure='1 kilo').save() batata_lasanha = Measure.objects.get(ingredient=self.batata, recipe=self.lasanha) self.assertEqual(self.lasanha.ingredients.all()[0].name, 'batata') self.assertEqual(batata_lasanha.measure, '1 kilo') def test_no_double_ingredients(self): self.batata.save() self.lasanha.save() Measure.objects.create(ingredient=self.batata, recipe=self.lasanha, measure='uma') try: Measure.objects.create(ingredient=self.batata, recipe=self.lasanha, measure='duas') except ValidationError: pass self.assertEqual(self.lasanha.measure_set.all().count(), 1)
def handle_ingredient(self, recipe, name, amount, ingredientid, grams): self.stdout.write(u"\t - ingredient: %s | %s" % (amount, name)) # Look for food ingredient = Ingredient.objects.search(name) if not ingredient: if self.create_foods: ingredient = Ingredient() ingredient.NDB_No = self.ingredient_NDB_No_generator(); ingredient.Shrt_Desc = name ingredient.Long_Desc = name ingredient.save() else: raise Exception("Ingredient failed!") ing_amount = IngredientWithAmount(Recipe=recipe, Ingredient=ingredient) ing_amount.HumanReadable = u"%s %s" % (amount, name) ing_amount.GramsEquiv = grams # Quantity and Units items = amount.split() try: ing_amount.Quantity = float(sum(Fraction(part) for part in items[0].split())) if len(items) == 1: ing_amount.Units = u"unit" else: ing_amount.Units = items[-1] self.stdout.write(u"\t + ingredient: %s" % (ingredient.Shrt_Desc)) self.stdout.write(u"\t + quantity: %s" % (ing_amount.Quantity)) self.stdout.write(u"\t + units: %s" % (ing_amount.Units)) ing_amount.save() except Exception as e: self.stderr.write(str(e)) ingredient.delete() raise Exception("Quanty and units not parseable: %r" % amount)
def editRecipeIngredients(request, recipe): """ Saves the current RecipeIngredients objects for the current recipe. """ recipeIngredients = Recipeingredients.objects.filter(recipe=recipe) quantity_str = "quantity" ingredient_str = "ingredient" for x in recipeIngredients: i= request.POST.get(ingredient_str + str(x.id)).strip() quantity = request.POST.get(quantity_str + str(x.id)).strip() if quantity and i: existingIngredient = Ingredient.objects.filter(name=i) if not len(existingIngredient) == 0: for ingredient in existingIngredient: x.ingredient = ingredient x.quantity = quantity else: ingredient = Ingredient() ingredient.name = i ingredient.save() x.ingredient = ingredient x.quantity = quantity x.save()
def create_ingredient(label, order, recipe): ingredient = Ingredient() ingredient.label = label ingredient.order = order ingredient.recipe = recipe ingredient.save() return ingredient
class IngredientModelTest(TestCase): def setUp(self): self.batata = Ingredient(name='batata') self.cenoura = Ingredient(name='cenoura') def test_ingredient_is_saved(self): self.batata.save() self.assertEqual(Ingredient.objects.all()[0].name, 'batata')
def handle(self, *args, **options): if Ingredient.objects.exists(): print('Aromas data already loaded...exiting.') print(ALREDY_LOADED_ERROR_MESSAGE) return print("Creating Ingredients data") for row in DictReader(open('./ingredient_by_id.csv', encoding="utf-8"), delimiter=','): ingredient = Ingredient() ingredient.entity_id = row['entity_id'] ingredient.entity_alias_readable = row['entity_alias_readable'] ingredient.save() print("Ingredients data successfully created")
def _create_recipe(author, name, tag): products = [ Product.objects.create(title=f'testIng{i}', unit=i) for i in range(2) ] recipe = Recipe(author=author, name=name, description='test test test', cook_time=5) recipe.save() recipe.tags.add(tag) for product in products: ingredient = Ingredient(recipe=recipe, ingredient=product, amount=2) ingredient.save() return recipe
class MeasureRelationTest(TestCase): def setUp(self): self.lasanha = Recipe(title='lasanha', description='placeholder') self.batata = Ingredient(name='batata') def test_create_association(self): self.lasanha.save() self.batata.save() Measure(ingredient=self.batata, recipe=self.lasanha, measure='1 kilo').save() batata_lasanha = Measure.objects.get(ingredient=self.batata, recipe=self.lasanha) self.assertEqual(self.lasanha.ingredients.all()[0].name, 'batata') self.assertEqual(batata_lasanha.measure, '1 kilo')
def get_ingredients(self, dry_run=True): with connections['newsstand'].cursor() as cursor: if not dry_run: cursor.execute( 'SELECT item, skillline, reagent, quantity, spell FROM newsstand.tblDBCItemReagents' ) columns = [col[0] for col in cursor.description] for row in fetchsome(cursor): ingredient = dict(zip(columns, row)) try: crafted_item = Item.objects.get( blizzard_id=ingredient['item']) recipe_spell = Recipe.objects.get( blizzard_id=ingredient['spell']) except Item.DoesNotExist: self.stdout.write('Item {} not found'.format( ingredient['spell'])) continue except Recipe.DoesNotExist: self.stdout.write('Recipe {} not found'.format( ingredient['spell'])) continue try: ingredient_reagent = Item.objects.get( blizzard_id=ingredient['reagent']) except Item.DoesNotExist: self.stdout.write('Reagent {} not found'.format( ingredient['spell'])) continue if Ingredient.objects.filter(reagent=ingredient_reagent, spell=recipe_spell).exists(): continue else: new_ingredient = Ingredient() new_ingredient.item = crafted_item new_ingredient.skillline = ingredient['skillline'] new_ingredient.reagent = ingredient_reagent new_ingredient.quantity = ingredient['quantity'] new_ingredient.spell = recipe_spell new_ingredient.save() else: self.stdout.write("Skipping Ingredients")
class MeasureRelationTest(TestCase): def setUp(self): self.user = User.objects.create(username='******', password='******') self.lasanha = Recipe(title='lasanha', description='placeholder', author=self.user) self.batata = Ingredient(name='batata') @mock.patch('recipes.models.Recipe.indexing', new=mock_indexing) def test_create_association(self): self.lasanha.save() self.batata.save() Measure(ingredient=self.batata, recipe=self.lasanha, measure='1 kilo').save() batata_lasanha = Measure.objects.get(ingredient=self.batata, recipe=self.lasanha) self.assertEqual(self.lasanha.ingredients.all()[0].name, 'batata') self.assertEqual(batata_lasanha.measure, '1 kilo')
def handle(self, *args, **options): with open('ingredients.json', 'r', encoding='utf-8') as fh: data = json.load(fh) for i in data: dimension = i['dimension'] title = i['title'] if not Ingredient.objects.filter(title=title).exists(): print(f'Добавляю {title}') if dimension in [ 'по вкусу', 'стакан', 'кусок', 'горсть', 'банка', 'тушка', 'пакет' ]: dimension = 'г' ingredient = Ingredient(title=title, dimension=dimension) ingredient.save() return '--Ингредиенты добавлены--'
def post(self, request, pk): f = get_object_or_404(Recipe, id=pk) ingredient = Ingredient(name = request.POST['ingredient'], measurement=request.POST['measurement'], owner=request.user, recipe=f) ingredient.save() return redirect(reverse('recipes:recipe_update', args=[pk]))
def mutate(root, info, name, notes, category_id): category = IngredientCategory.objects.get(id=category_id) igi = Ingredient(name=name, notes=notes, category=category) ok = True igi.save() return CreateIngredient(ingredient=igi, ok=ok)
def handle_recipe(self, data, url): if Recipe.objects.filter(URL=url).exists(): self.stdout.write(u"\t already in database") return 1, False recipe = Recipe(Title=data[u"name"], URL=url) self.stdout.write(u"\t - author: %s" % data.get(u"author", None)) recipe.Author = data.get(u"author", None) self.stdout.write(u"\t - image: %s" % data.get(u"image", None)) recipe.Image = data.get(u"image", None) self.stdout.write(u"\t - ratingValue: %s" % data.get(u"ratingValue", None)) recipe.Rating = data.get(u"ratingValue", None) self.stdout.write(u"\t - description: %s" % data.get(u"description", '')[:60]) recipe.Description = data.get(u"description", None) # Produces self.stdout.write(u"\t - Produces: %s" % data[u"name"]) ingredient = Ingredient.objects.search(data[u"name"]) if not ingredient: if self.create_foods: ingredient = Ingredient() ingredient.NDB_No = self.ingredient_NDB_No_generator(); ingredient.Shrt_Desc = data[u"name"] ingredient.Long_Desc = data[u"name"] ingredient.save() else: return None, False recipe.Produces = ingredient # Yields self.stdout.write(u"\t - yields: %s" % data.get(u"yields", None)) yields = data.get(u"yields", None) if yields: items = [it for it in yields.split() if it.isdigit()] if items: recipe.Yields = items[0] self.stdout.write(u"\t + yields: %s -> %s" % (yields, recipe.Yields)) # PrepTime and CookTime def minutes(value_str): if value_str: t = parse_duration(value_str) return int(t.seconds/60.) return None self.stdout.write(u"\t - prepTime: %s" % minutes(data.get(u"prepTime", None))) self.stdout.write(u"\t - cookTime: %s" % minutes(data.get(u"cookTime", None))) recipe.PrepTime = minutes(data.get(u"prepTime", None)) recipe.CookTime = minutes(data.get(u"cookTime", None)) recipe.save() # Ingredients try: for name, amount, ingredientid, grams in zip(data[u"ingredients-name"], data[u"ingredients-amount"], data["ingredients-data-ingredientid"], data[u"ingredients-data-grams"]): self.handle_ingredient(recipe, name, amount, ingredientid, grams) except Exception as e: self.stderr.write(str(e)) recipe.delete() # Al borrar el recipe, se borran todos los relacionados (IngredientWithAmount) para no quedar huérfanos return None, False #Directions try: i = 1 self.stdout.write(u"\t - directions:") for direction in data.get(u"directions"): d = Direction(Recipe=recipe, StepNumber=i) d.Description = direction d.save() self.stdout.write(u"\t + %s" % d) i += 1 except Exception as e: self.stderr.write(str(e)) recipe.delete() # Al borrar el recipe, se borran todos los relacionados (IngredientWithAmount) para no quedar huérfanos return None, False return recipe, True
def test_inserting_into_db(self): """it should insert into the database""" ingredient = Ingredient(name='test', amount=1) ingredient.save() assert Ingredient.objects.filter(name='test').count() == 1
def handle(self, *args, **options): i = Ingredient(name=' '.join(options['name']), type=options['type']) i.full_clean() i.save() self.stdout.write(str(i.pk))
import csv from recipes.models import Ingredient, Tag with open('./recipes/ingredients.csv', newline='', encoding='utf-8') as File: reader = csv.reader(File) for row in reader: ingred = Ingredient(title=row[0], dimension=row[1]) ingred.save() #test tags = ['B', 'L', 'D'] for tag in tags: new_tag = Tag(tag_name=tag) new_tag.save()
def handle_recipe(self, data, url): if Recipe.objects.filter(URL=url).exists(): self.stdout.write(u"\t already in database") return 1, False recipe = Recipe(Title=data[u"name"], URL=url) self.stdout.write(u"\t - author: %s" % data.get(u"author", None)) recipe.Author = data.get(u"author", None) self.stdout.write(u"\t - image: %s" % data.get(u"image", None)) recipe.Image = data.get(u"image", None) self.stdout.write(u"\t - ratingValue: %s" % data.get(u"ratingValue", None)) recipe.Rating = data.get(u"ratingValue", None) self.stdout.write(u"\t - description: %s" % data.get(u"description", '')[:60]) recipe.Description = data.get(u"description", None) # Produces self.stdout.write(u"\t - Produces: %s" % data[u"name"]) ingredient = Ingredient.objects.search(data[u"name"]) if not ingredient: if self.create_foods: ingredient = Ingredient() ingredient.NDB_No = self.ingredient_NDB_No_generator() ingredient.Shrt_Desc = data[u"name"] ingredient.Long_Desc = data[u"name"] ingredient.save() else: return None, False recipe.Produces = ingredient # Yields self.stdout.write(u"\t - yields: %s" % data.get(u"yields", None)) yields = data.get(u"yields", None) if yields: items = [it for it in yields.split() if it.isdigit()] if items: recipe.Yields = items[0] self.stdout.write(u"\t + yields: %s -> %s" % (yields, recipe.Yields)) # PrepTime and CookTime def minutes(value_str): if value_str: t = parse_duration(value_str) return int(t.seconds / 60.) return None self.stdout.write(u"\t - prepTime: %s" % minutes(data.get(u"prepTime", None))) self.stdout.write(u"\t - cookTime: %s" % minutes(data.get(u"cookTime", None))) recipe.PrepTime = minutes(data.get(u"prepTime", None)) recipe.CookTime = minutes(data.get(u"cookTime", None)) recipe.save() # Ingredients try: for name, amount, ingredientid, grams in zip( data[u"ingredients-name"], data[u"ingredients-amount"], data["ingredients-data-ingredientid"], data[u"ingredients-data-grams"]): self.handle_ingredient(recipe, name, amount, ingredientid, grams) except Exception as e: self.stderr.write(str(e)) recipe.delete( ) # Al borrar el recipe, se borran todos los relacionados (IngredientWithAmount) para no quedar huérfanos return None, False #Directions try: i = 1 self.stdout.write(u"\t - directions:") for direction in data.get(u"directions"): d = Direction(Recipe=recipe, StepNumber=i) d.Description = direction d.save() self.stdout.write(u"\t + %s" % d) i += 1 except Exception as e: self.stderr.write(str(e)) recipe.delete( ) # Al borrar el recipe, se borran todos los relacionados (IngredientWithAmount) para no quedar huérfanos return None, False return recipe, True
from django.contrib.auth import get_user_model from recipes.models import Recipe, Comment, Like, Ingredient, Complaint from django.utils import timezone from datetime import datetime, date, time UserModel = get_user_model() for i in range(100): k = str(i) recipe = Recipe(title = 'title'+k ,text = 'text' + k, preview ='preview' + k) recipe.author = UserModel.objects.get(pk = 1) recipe.save() ingredient = Ingredient (ingredient_name = 'ingredient' + k) ingredient.dish = Recipe.objects.get(pk = i+1) ingredient.save() comment = Comment(creator=)