ORMs are powerful tools that map Python objects and their relations with one another to database structures.
Using an ORM has its limits: in many cases it helps to actually understand what is going on behind the scenes, for example to avoid performance problems, and occasionally even the best ORMs won't be able to represent your complex SQL query, forcing you to write SQL by hand again. Then again, ORMs automatically and trivially protect you against one of the most frequent, easy to exploit, and dangerous attack vectors: SQL injections.
How does this all work? How can an ORM perform these translations? Starting from a database connector, we will write a small ORM with the following features:
- defining database tables through model definitions as Python classes
- linking these models through foreign-key relations
- a query engine that can do all the common operations while feeling (at least somewhat) Pythonic
Animal.select(where=Animal.type == "snake") Animal.select().order_by(Animal.name.asc).limit(10).filter((Animal.age > 1) & (Animal.age < 5))
Affiliation: solute GmbH
Jonathan studied Computational Linguistics, Cognitive Science and Computer Science, and works as a software developer since finishing his various degrees. He fell in love with Python during university, and for the most part has been faithful to it. Outside of work, he either works on esoteric programming languages, or writes esoteric (read: terrible) Python code.