An intro to ORM and SQLAlchemy.
As per the official documentation- “SQLAlchemy is the Python SQL toolkit and Object Relational Mapper that gives application developers the full power and flexibility of SQL.”
But…
Before we begin our discussion let’s once go through are basics. So first up,
What is SQL?
SQL stands for Structured Query Language. It’s a language for interacting with relational databases. Relational databases are structured like a traditional table with columns and rows.
Coming back to our discussion👀
In simple words, SQLAlchemy is a set of tools to access various SQL databases like SQL, MySQL or PostgresSQL. It is a Python code library that transfers data stored in a SQL database into Python objects, you can simply use Python code to create, read, update, and delete data instead of writing straight SQL.
But how does it transfer data stored in a SQL database into Python objects?
That’s where O-R-M or object-relational mapper comes into play.
As stated in the official documentation, SQLAlchemy is an O-R-M or object-relational mapper. All you have to do is define a python class and SQLAlchemy will translate that python class into the table in our database and allow you to perform different CRUD operations. This technique is called ORM. So by turning database records into objects, it helps automate redundant tasks while the developer remains in control of how the database is organized and how SQL is constructed.
Image reference: fullstackpython.com
Why should you use SQLAlchemy?
- Schema modification
SQLAlchemy helps you synchronize models and schemas using the alembic add-on, you can change the schema in the code environment and then run the following terminal command:
$ alembic upgrade head
- A useful tool in the testing phase
SQLAlchemy Core comes with the connect function that is used along with an engine that helps you maintain and manage database connections with ease. Accurate use of connection ensures that there is one and only one connection throughout the testing process.
- Table relationship organization
SQLAlchemy has an option called Lazy Loading, which enables users to specify how they want to get records for the database. Users can choose to get data from a table (lazy = ‘select’), data from joined tables (lazy = ‘joined’), or objects to continue querying later (lazy = ‘dynamic’).
You can now go ahead and use it to help speed up development time with SQLAlchemy!🚀
Thank you for reading this post, stay tuned for my next blog posts.
You can find me on Twitter, LinkedIn and Github.✨