ORM in Python Flask
ORM in flask a quick start tutorial
What is ORM?
ORM(Object Relationship Mapping) is a programming construct where the DB tables are treated as objects, and the operations on top of them are carried out via functions.
Video Tutorial
ORM in Python
Django, the web framework in Python, has one of the most solid ORMs. For non-Django applications, SQLAlchemy has proved to be effective.
ORM in Flask
Flask doesn't support ORM out of the box, but with the help of flask-sqlalchemy
, we can achieve the ORM functionalities.
Installation
Documentation For Reference
Flask SQLalchemy has extensive documentation.
https://flask-sqlalchemy.palletsprojects.com/en/2.x/
Configure DB
Let's start writing some code. Open a Python file orm_example.py.
Import flask-sqlalchemy and connect to the DB
Defining a Model
Each table is called a Model(a Python class) when defining an ORM. The table columns will become attributes of the class.
Creating the Table
The above snippet is just a configuration to create a table in DB. You need to use
CRUD Operations
Create a new Item
List all items
Filter Items
GET by id
Selecting Specific Columns
Update an Item
Delete an Item
Run the script
How to add One-Many and Many-Many relationship
Checkout the following snippet
https://github.com/bhavaniravi/work-tracker/blob/main/application/models.py
Exercise
Pick one model for your application
Add the Model and fields
Try all the CRUD operations
Last updated