104 lines
2.6 KiB
Python
104 lines
2.6 KiB
Python
from django.db import models
|
|
|
|
# Create your models here.
|
|
|
|
"""
|
|
Recipe's creation workflow :
|
|
|
|
1. Create recipe with required info, optional preparation
|
|
2. Create recipe's list of ingredients
|
|
a. Create new ingredients instances
|
|
b. Create IngredientWithAmount instances
|
|
3. Add preparation steps if necessary
|
|
|
|
"""
|
|
|
|
|
|
class Recipe(models.Model):
|
|
name = models.CharField(max_length=512)
|
|
category = models.CharField(
|
|
max_length=2,
|
|
choices=(
|
|
('0', 'Petit-déjeuner'),
|
|
('1', 'Entrée'),
|
|
('2', 'Plat'),
|
|
('3', 'Dessert'),
|
|
))
|
|
ingredients = models.ManyToManyField(
|
|
'Ingredient',
|
|
through='IngredientWithAmount'
|
|
)
|
|
|
|
def __str__(self):
|
|
return "{}".format(self.name)
|
|
|
|
|
|
class Ingredient(models.Model):
|
|
name = models.CharField(max_length=256)
|
|
|
|
def __str__(self):
|
|
return "{}".format(self.name)
|
|
|
|
|
|
class IngredientWithAmount(models.Model):
|
|
""" A recipe-ingredient relation associated with amounts
|
|
"""
|
|
|
|
recipe = models.ForeignKey(
|
|
'Recipe',
|
|
models.CASCADE)
|
|
ingredient = models.ForeignKey(
|
|
'Ingredient',
|
|
models.CASCADE )
|
|
amount = models.DecimalField(
|
|
max_digits=6,
|
|
decimal_places=2,
|
|
)
|
|
unit = models.CharField(
|
|
max_length=2,
|
|
choices=(
|
|
('gr', 'Grammes'),
|
|
('u', 'Units'),
|
|
('l', 'Litres'),
|
|
))
|
|
|
|
def __repr__(self):
|
|
return "<{}>".format(self.display())
|
|
|
|
def display(self):
|
|
""" Print info in a human friendly way.
|
|
|
|
* Correct grammar
|
|
* Apropriate units according to amount
|
|
"""
|
|
# Note: amount has a .is_integer() method :)
|
|
amount = self.amount
|
|
name = self.ingredient.name.lower()
|
|
particule = ""
|
|
unit = ""
|
|
if self.unit == 'u':
|
|
integer = int(amount)
|
|
fraction = amount - integer
|
|
# Print subfractions of one as ratio
|
|
if fraction: #TODO: if is not integer...
|
|
fraction = "{}/{}".format(
|
|
*amount.as_integer_ratio()
|
|
)
|
|
else:
|
|
fraction = ""
|
|
if integer:
|
|
# Plural
|
|
if integer >= 2:
|
|
name += "s"
|
|
integer = str(integer)
|
|
else:
|
|
integer = ""
|
|
amount = "{}{}".format(integer, fraction)
|
|
else:
|
|
particule = "de "
|
|
unit = self.unit
|
|
|
|
return "{}{} {}{}".format(
|
|
amount, unit, particule, name
|
|
)
|