Home > Enterprise >  Creating a Django Model for a recipe
Creating a Django Model for a recipe

Time:04-27

I am trying to create a Django model for a recipe database. I'm having trouble writing a model that will account for a variable amount of ingredients(not every recipe has the same amount of ingredients). Here is what I have so far:

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

    def __str__(self):
        return self.recipe

I'm stuck trying to figure out how to associate one recipe with multiple ingredients in the database. Right now, I've only managed to create one ingredient per recipe. The foreign keys are for other created classes that describe individual ingredients and cuisines.

CodePudding user response:

There are two solutions here:

  1. Put the foreign key in the ingredients class:

    class Ingredients(models.Model):
        ...
        recipe = models.ForeignKey(Recipe, on_delete=models.CASCADE)
    

    This associates each ingredient with a recipe and allows each recipe to have multiple ingredients.

  2. Use a ManyToManyField in the recipe:

    class Recipe(models.Model):
       ...
       ingredients = models.ManyToManyField(Ingredient)
    

    This allows you to add the same ingredient to multiple recipes and each recipe has multiple ingredients.

  • Related