Sitemap

Object-Relational Mapping (ORM)

1 min readAug 28, 2023

--

Object-Relational Mapping is a technique which creates a bridge between an object oriented programming language and a relational Database. It allows a better way to interact with database which not only improves the user experience but also more modular and more secure.

What is an ORM Tool?

An ORM tool is a software designed to help in interacting with the database. There are plenty of tools available to help with the process of bridging between the OOP and a relational database such as Hibernate, Entity Framework, Sequelize, SQLAlchemy, and Dapper.

Why to use an ORM Tool at all?

Get Harpreet Singh’s stories in your inbox

Join Medium for free to get updates from this writer.

There are plenty of reason why we should use the ORM:

  1. It helps in reducing the repetitive code.
  2. Helps in implementation of conventional patterns that are organized and logical.
  3. It improves the security helping in reducing the chances of SQL Injection attacks.
  4. It speeds up the development process.

Defining Tables with SQLAlchemy ORM

In order to create a table with SQLAlchemy there are 4 things needed:

  1. Inheritance from a declarative base object which basically stores the collection of classes and mapped tables in the declarative system.
  2. A __tablename__(Dunder) class attribute.
  3. One or more than one column as class attribute.
  4. A primary key to uniquely identify each row of a table.
from sqlalchemy import Column, Integer, String, ForeignKey, DateTime
from sqlalchemy.orm import declarative_base, relationship, backref

Base = declarative_base()


class User(Base):
__tablename__ = "users"

id = Column(Integer, primary_key=True)
name = Column(String, nullable=False)
email = Column(String(55), nullable=False)

item = relationship("Item", backref="users")

--

--