ORM Relationships — ELI5

Think about how people in your life are connected. You have one mom (one-to-one). Your mom might have several kids (one-to-many). And your friends can also be friends with each other — everyone can have many friends, and each friend has many friends back (many-to-many).

Databases store information in separate tables, kind of like different spreadsheets. One spreadsheet has users, another has orders, another has products. But those things are connected — a user places an order, and an order contains products.

An ORM (Object-Relational Mapper) lets you work with database tables as if they were Python objects. Instead of writing database commands, you write Python code like user.orders to get all of a user’s orders.

Relationships are the glue that connects these objects. When you define a relationship, you’re telling the ORM: “These two things are connected, and here’s how.”

There are three main types:

  • One-to-one: A user has one profile. A profile belongs to one user. Like a person and their passport.
  • One-to-many: A teacher has many students. Each student has one teacher (in a class). Like a hen and her chicks.
  • Many-to-many: Students take many courses. Each course has many students. Like friendship — it goes both ways and everyone can have lots.

The ORM handles all the behind-the-scenes database work. You just say user.orders and get a list of order objects. You don’t need to know which columns match up or how the database joins things together.

One thing to remember: Relationships let you navigate between connected data using simple Python — user.orders, order.items, item.product — instead of writing database queries by hand.

pythondatabasesorm

See Also

  • Python Aioredis Understand Aioredis through a practical analogy so your Python decisions become faster and clearer.
  • Python Alembic Understand Alembic through a practical analogy so your Python decisions become faster and clearer.
  • Python Asyncpg Database asyncpg is the fastest way for Python to talk to PostgreSQL without making your program sit around waiting.
  • Python Asyncpg Understand Asyncpg through a practical analogy so your Python decisions become faster and clearer.
  • Python Cassandra Python Understand Cassandra Python through a practical analogy so your Python decisions become faster and clearer.