FastAPI - Beginner to Pro / Authentication & Authorization

One to Many Relationship

🔗 What is a One-to-Many Relationship?

When discussing SQL tables, a one-to-many relationship means:

One record in a table can be related to multiple records in another table,

but each of those records belongs to only one parent record.

In our application:

  • A single user can have multiple todos.

  • A single todo cannot belong to multiple users.

If you are a user, you might have:

  • “Take out the garbage”

  • “Get a haircut”

  • “Take a shower”

All of these todos belong to you — and only you.

At the same time, the system can contain many users, each with their own list of todos.

That is the meaning of:

✔ One User

✔ Many Todos


🗄️ Users & Todos — Two Separate Tables

From a backend and database design perspective, we are working with two separate tables.

1️⃣ Users Table

This table stores authentication and identity data.

id (PK)

email

username

first_name

last_name

hashed_password

is_active

1

codeveda@gmail.com

codeveda1

code

veda

13ieidq80hscd…

1

2

example@gmail.com

example

example

user

uqwb38223jd…

1

Important Concept

  • PK (Primary Key) uniquely identifies each user.

  • No two users can share the same primary key.

  • The primary key is how the database distinguishes records internally.


2️⃣ Todos Table (Before Relationship)

Originally, our todos table looked like this:

id (PK)

title

description

priority

complete

But here’s the problem:

👉 There is no connection between a todo and a user.

So how does the database know which todo belongs to which user?

It doesn’t.


🔑 Introducing the Foreign Key

To connect the two tables, we must add a new column to the Todos table:

owner

This column will store the user’s primary key.

Now our todos table becomes:

id (PK)

title

description

priority

complete

owner (FK)

What Does FK Mean?

  • FK = Foreign Key

  • A foreign key references a primary key in another table.

  • It creates the relationship between tables.

In our case:

todos.owner  →  users.id

This means:

The owner column in the todos table references the id column in the users table.


📊 Real Example With Data

Let’s look at actual data.

Users Table

id (PK)

email

username

1

codeveda@gmail.com

codeveda1

2

example@gmail.com

example

Todos Table (With Foreign Key)

id

title

priority

complete

owner (FK)

1

Go to store

4

0

1

2

Haircut

3

0

1

3

Feed dog

5

0

2

4

Water Plant

4

0

2

5

Learn something New

5

0

1

6

Shower

5

0

2


🔎 Understanding What’s Happening

Let’s analyze this carefully.

All records with:

owner = 1

Belong to:

users.id = 1

That is → codeveda1

So todos 1, 2, and 5 belong to user 1.

All records with:

owner = 2

Belong to:

users.id = 2

That is → example user

So todos 3, 4, and 6 belong to user 2.