SQLAlchemy ORM - Adding Objects
Last Updated :
18 Mar, 2022
In this article, we will discuss how to add objects in the SQLAlchemy ORM.
The SQLAlchemy Object Relational Mapper presents a method of associating user-defined Python classes with database tables and instances of those classes (objects) with rows in their corresponding tables. For this article, we're going to use the Postgres database. You can also use an in-memory-only SQL database.
Make sure you've properly installed sqlalchemy if not then install it with:
pip install sqlachemy
For example, You've designed an API that stores and fetches the posts created by the user in the database, somewhat like GFG, Instagram, etc. This is the class that is mapped to our database table "posts"
Python3
from sqlalchemy import Column, Integer, String, Boolean
from sqlalchemy.ext.declarative import declarative_base
# Declare Mapping
Base = declarative_base()
# This is the class which is mapped to "posts"
# table to our database
class Post(Base):
__tablename__ = "posts"
id = Column(Integer, primary_key=True, nullable=False)
title = Column(String, nullable=False)
content = Column(String, nullable=False)
published = Column(Boolean, server_default='true', nullable=False)
Stepwise Implementation
Step 1: Database related configuration
Python3
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker
# Syntax of database url = "<database_vendor_name>:
# //<username>:<password>@ip-address/hostname/
# <database_name>"
DB_URL = "postgresql://anurag:anurag@localhost/gfg"
engine = create_engine(DB_URL)
local_session = sessionmaker(autoflush=False,
autocommit=False, bind=engine)
# With this we get a session to do whatever
# we want to do
db = local_session()
Step 2: To add a new object (post)
Here, we are creating an object, and then with the use of the db.add() function, we have added the created object to the database.
Python3
# New post created by a user, assumes
# you get this from the frontend
post = Post(title="GFG Article",
content="How to add SQL Alchemy objects",
published=True)
db.add(post)
As you can see above post is not saved to the database till you committed it like,
Python3
# To store the object to the database,
# otherwise the transaction remains pending
db.commit()
# After performing transaction, we should
# always close our connection to the database
# It's a good practice and we must follow it
db.close()
print("Successfully added a new post")
Note: Every time you made changes make sure that you've committed the transaction, otherwise the transaction is pending.
After committing the transaction you've successfully saved a new object to your database, you can query the database regarding the changes
Step 3: Querying the database
Under this, we are verifying if the object is successfully added or not. If it is added then the database will show the same object else it won't be present in the database.
SELECT * FROM posts;
And you get all your posts saved in your local database.
Complete Script to add new objects to the database:
Python3
from sqlalchemy import Column, Integer, Boolean, String
from sqlalchemy import create_engine
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker
# Declare Mapping
Base = declarative_base()
# This is the class which is mapped to "posts"
# table to our database
class Post(Base):
__tablename__ = "posts"
id = Column(Integer, primary_key=True, nullable=False)
title = Column(String, nullable=False)
content = Column(String, nullable=False)
published = Column(Boolean, server_default='true', nullable=False)
# Syntax of database url = "<database_vendor_name>://
# <username>:<password>@ip-address/hostname/<database_name>"
DB_URL = "postgresql://anurag:anurag@localhost/gfg"
engine = create_engine(DB_URL)
local_session = sessionmaker(autoflush=False, autocommit=False, bind=engine)
# With this we get a session to do whatever we
# want to do
db = local_session()
# New post created by a user, assumes you get this
# from the frontend
post = Post(title="GFG Article",
content="How to add SQL Alchemy objects", published=True)
db.add(post)
db.commit()
# After performing transaction, we should always close
# our connection to the database
db.close()
print("Successfully added a new post")
Output:
Similar Reads
Django ORM vs SQLAlchemy For relational database newbies who are Python developers, Django ORM and SQLAlchemy are two heavyweights worth considering. As Object-Relational Mappers (ORMs) they act as middlemen between Pythonic objects and database tables thereby simplifying how we interact with data.vsNevertheless making choi
10 min read
SQLAlchemy Cascading Deletes SQLAlchemy is a powerful ORM (Object-Relational Mapping) library for Python that allows developers to interact with relational databases using Python objects. It provides a rich set of tools for querying, updating, and manipulating data, making it a popular choice for building web applications and o
4 min read
SQLAlchemy ORM - Creating Session In this article, we will see how to create a session for SQLAlchemy ORM queries. Before we begin, let us install the required dependencies using pip: pip install sqlalchemySince we are going to use MySQL in this post, we will also install a SQL connector for MySQL in Python. However, none of the cod
3 min read
SQLAlchemy Core - Conjunctions SQLAlchemy is a popular Python programming SQL toolkit and Object Relational Mapper that gives application developers the full power and flexibility of SQL in a Pythonic way. SQLAlchemy ORM or object-relational mapper is a component that provides an abstraction layer over the SQL database which mak
6 min read
SQLAlchemy ORM - Declaring Mapping In this article, we will see how to declare mapping using SQLAlchemy in Python. You will need a database (MySQL, PostgreSQL, SQLite, etc) to work with. Since we are going to use MySQL in this post, we will also install a SQL connector for MySQL in Python. However, none of the code implementations ch
4 min read
SQLAlchemy - Introduction SQLAlchemy is basically referred to as the toolkit of Python SQL that provides developers with the flexibility of using the SQL database. The benefit of using this particular library is to allow Python developers to work with the language's own objects, and not write separate SQL queries. They can b
3 min read
Python Falcon - SQLAlchemy Models Python Falcon is an up-to-date web framework with an adjustable applicative architecture that is oriented to creating high-speed application processes and APIs. Another often implemented pattern is CRUD and interaction with the database can be facilitated with the help of SQLAlchemy for Python. When
5 min read
Floor division in SQLAlchemy In this article, we will see how to perform floor division in SQLAlchemy against a PostgreSQL database in python. Floor division is performed in different methods using different functions. Such kinds of mathematical operations are database-dependent. In PostgreSQL, floor division is performed using
2 min read
SQLAlchemy Core - Using Aliases In this article, we are going to see Aliases in SQLAlchemy Core using Python. Creating table for demonstration Import necessary functions from the SQLAlchemy package. Establish connection with the PostgreSQL database using create_engine() function as shown below. Create a table called books with col
2 min read
JSONB - Sqlalchemy One of the most well-liked relational database management systems (RDBMS) in the world, PostgreSQL is quite strong and allows developers access to a wide range of complex capabilities. One of the most useful features provided by Postgres is the support for JSON data types, together with the ability
5 min read