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.
The above snippet is just a configuration to create a table in DB. You need to use
db.create_all()
CRUD Operations
Create a new Item
# creates a Python Object
admin = User(username='admin', email='admin@example.com')
# adds to the db session
db.session.add(admin)
# Makes the entry in the DB
# you can do multiple db.session.add before committing
db.session.commit()
List all items
users = User.query.all()
results = []
for user in users:
results.append({
"username": user.name,
"email": user.email
})
Filter Items
users = User.query.filter_by(username='admin').all()
# use the same for loop as above
GET by id
user = User.query.filter_by(id=1).first()
result = {
"name": user.name,
"email": user.email
}
Selecting Specific Columns
fields = ["book_id", "book_name", "author"]
field_objects = [getattr(Book, "name") for field in fields]
books = Book.query.with_entities(*field_objects).all()