Creating a Django Model for a recipe #2

Viewed 102

This is a follow-up question to Creating a Django Model for a recipe. I am able to select multiple ingredients for a single recipe, but my code only allows for one general quantity selection that associates with all ingredients selected. For example: (BLT recipe) I can select Bacon, Lettuce, and Tomato, but I am not able to have different quantities for each (i.e. Bacon(1), Lettuce(1), Tomato(2).

class Recipe(models.Model):
    '''A recipe class to input new recipes'''
    recipe = models.CharField(max_length=50)
    ingredient = models.ManyToManyField(Ingredient)
    quantity = models.CharField(max_length=1)
    cuisine = models.ForeignKey(Cuisine, null=True, on_delete=models.SET_NULL)

    def __str__(self):
        return self.recipe

class Ingredient(models.Model):
    '''All ingredients for any recipe or individual selection'''
    ingredient = models.CharField(max_length=50)
    department = models.ForeignKey(Department, null=True, on_delete=models.SET_NULL)

    def __str__(self):
        return self.ingredient
1 Answers

my code only allows for one general quantity selection that associates with all ingredients selected

class Recipe(models.Model):
    '''A recipe class to input new recipes'''
    recipe = models.CharField(max_length=50)
    ingredient = models.ManyToManyField(Ingredient)
    quantity = models.CharField(max_length=1)
    cuisine = models.ForeignKey(Cuisine, null=True, on_delete=models.SET_NULL)

    def __str__(self):
        return self.recipe

Contrary to what you describe in English, you associate quantity with a recipe, not with ingredients. Since it doesn't make sense for there to be one quantity per recipe, quantity doesn't belong in the Recipe class. Instead, quantity should be in the Ingredient class because each ingredient has a quantity.

Related