VOOZH about

URL: https://www.geeksforgeeks.org/python/sqlalchemy-orm-adding-objects/

⇱ SQLAlchemy ORM - Adding Objects - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

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

Stepwise Implementation

Step 1: Database related configuration

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.

👁 Image

As you can see above post is not saved to the database till you committed it like,

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.

👁 Image

Complete Script to add new objects to the database:

Output:

👁 Image
Comment