Building a very simple ORM

Posted by Jonas Sandström on Mon 05 September 2022

I've stumbled across two great resources for building simple ORMs in Python. With simple I mean "As simple as it can get" and therefore far from something you would like to put into production in a business critical system... But as always great for learning and understanding how ORMs (like sqlalchemy or the Django ORM) works, and most importantly it's fun to write!

The resources

"Let's Build an ORM" - Greg Backc Youtube
Second part of a paid course on by Jahongir Rahmonov.

What is an ORM anyway?

The short answer is: an object oriented programming model that helps to bridge the gap between your classes and your database. Longer and more precise answers can be found all over the internet ;)

Instead of me writing about how to do this I just recommend you to watch the video. If that sparked your interest (as it did for me!) you can take a look at my implementation of a simple Postgres ORM on my github.

Here is my example file

from psql_orm import Database, Column, Table, ForeignKey

db = Database(

#  Create tables
class School(Table):
    country = Column(str)
    name = Column(str)

class Student(Table):
    name = Column(str)
    school = ForeignKey(School)


# Save school
school = School(name="Hogwarts", country="England")

# Save students
harry = Student(name="Harry Potter", school=school)
ron = Student(name="Ron Weasley", school=school)[harry, ron])

# Make queries
all_students = db.all(Student)
harrys_school = db.query(Student, name="Harry Potter")[0].school
hogwarts = db.query(School, country="Eng%")[0]  # use % for wildcard search.
assert ==