Designing Database Models
Introduction: The Role of Models in Our Cooking App
Welcome back! In the previous lesson, you learned how to set up the foundation of your project using a modern web framework. You organized your project files, configured the database connection, and prepared your app to serve static files and handle routes. Now, it's time to design the models that will represent recipes, ingredients, and reviews in your database.
Models are templates for your data. They define what kind of information your app will store and how different pieces of data relate to each other. In our cooking app, models will help us keep track of recipes, the ingredients they use, and the reviews users leave.
By the end of this lesson, you will understand how to design these models and how to represent their relationships in code using SQLAlchemy.
Quick Recall: FastAPI App and Database Setup
Before we dive in, let’s quickly remind ourselves of what we did in the previous lesson:
- We created a project structure for our app.
- We set up a database connection using SQLAlchemy.
- We prepared the app to serve static files and organized our routes.
This means our app is ready to store and manage data. Now, we need to decide what data to store and how to organize it. That’s where models come in.
From Real-World Concepts to ER Diagrams
Let’s start by thinking about the real-world things our app needs to keep track of:
- Recipes (like "Spaghetti Carbonara")
- Ingredients (like "eggs," "bacon," "spaghetti")
- Reviews (users rating and commenting on recipes)
To organize these, we use something called an Entity-Relationship (ER) diagram. This is a simple way to draw out how different types of data relate to each other.
Here’s a basic version for our app:
- A Recipe can have many Ingredients (and an ingredient can be used in many recipes).
- A Recipe can have many Reviews (but each review belongs to one recipe).
This diagram helps us plan how to structure our database tables and how they connect.
Understanding Primary Keys and Foreign Keys
Before we move on, let’s clarify two important concepts you’ll see in our models: primary keys and foreign keys.
