Adding Manual Recipes
Introduction: The Need for Manual Recipe Entry
Welcome back! So far, you have set up your project, designed your database models, and learned how to safely reset your database. Now, let’s take the next step: adding recipes to your app.
While it’s possible to add recipes automatically or through an API, sometimes you need a simple way to enter recipes by hand. This is especially useful for testing, quick data entry, or when you want to add a recipe that you found or created yourself. In this lesson, you’ll learn how to build a script that lets you add recipes directly from the command line. This script will prompt you for the recipe name, ingredients, and steps, then save everything to your database.
By the end of this lesson, you’ll be able to run a script, enter a new recipe, and see it appear in your app’s database.
Quick Recall: Models and Database Access
Before we dive in, let’s quickly remind ourselves of the key models and how we interact with the database. You’ve already created Recipe and Ingredient models. These models are connected by a many-to-many relationship, which means a recipe can have many ingredients, and an ingredient can belong to many recipes.
Here’s a reminder of what these models look like:
In this lesson, we’ll use these models and the built-in Object-Relational Mapper (ORM) to save new recipes and ingredients without writing raw database queries.
Preparing the Script Environment
To create a script that can add recipes, you need to make sure it can access your project settings and its database models. This requires a specific setup to initialize the environment before you can import your models.
Let’s look at how to set up the script:
osandsysare used to adjust the import path so the script can find your project modules.os.environ.setdefaultpoints to your project's settings file.django.setup()initializes the application environment, allowing you to use models outside of a standard web request.
