What is Declarative Mapping

This is the most common way of defining a mapping in SQLAlchemy. It involves defining a Python class and using special SQLAlchemy functions and decorators to define the columns, relationships, and other metadata of the table. This approach is simple and easy to use, and it allows you to define your mappings in a clear and concise way.

To use Declarative Mapping in SQLAlchemy, you need to do the following steps to consider:

  1. Create a base class for declarative mapping using the declarative_base function. This base class will be used as a base for all of your mapping classes.
  2. Define a mapping class for each table in your database. The mapping class should subclass the base class and define the columns of the table using Column objects. You can also use the __tablename__ attribute to specify the name of the table.
  3. Use the create_all method of the Base.metadata object to create the tables in the database.
  4. Use the sessionmaker function to create a session for querying the database.
  5. Use the query method of the session to query the database and retrieve instances of the mapping classes.
  6. Use the add method of the session to add new instances of the mapping classes to the database.
  7. Use the commit method of the session to save your changes to the database.

Example 

Here is an example of declarative mapping in SQLAlchemy, using an in-memory SQLite database. Here, we define a User class that represents a row in the user’s table. We use the __tablename__ attribute to specify the name of the table, and the Column class to define the columns of the table. Then, we create the user’s table in the database using the create_all method of Base.metadata.

Next, we create a Session object to manage the connection to the database and use it to add a new User object to the database and commit the changes. Finally, we use the session.query method to retrieve all rows from the user’s table and print the result.

Python3




from sqlalchemy import create_engine, Column, Integer, String
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker
  
# create an in-memory SQLite database
engine = create_engine('sqlite:///:memory:', echo=True)
  
Base = declarative_base()
  
class User(Base):
    __tablename__ = 'users'
    id = Column(Integer, primary_key=True)
    name = Column(String)
    fullname = Column(String)
    password = Column(String)
  
    def __repr__(self):
        return f"<User(name='{self.name}'
      fullname='{self.fullname}', password='{self.password}'>"
  
# create the users table
Base.metadata.create_all(engine)
  
# create a session to manage the connection to the database
Session = sessionmaker(bind=engine)
session = Session()
  
# add a new user to the database
user = User(name='john', fullname='John Doe', password='password')
session.add(user)
session.commit()
  
# query the users table
users = session.query(User).all()
print(users)
# Output: [<User(name='john', fullname='John Doe', password='password')>]


Output:

[<User(name='john', fullname='John Doe', password='password')>]

SQLAlchemy – Mapping Python Classes

SQLAlchemy is a popular Python library that provides a nice API for interacting with databases. One of its key features is the ability to map Python classes to database tables, allowing you to use Python objects to represent rows in a database table. This is known as an “object-relational mapper” (ORM).

Types of Mappings in Python Classes

In SQLAlchemy, there are several ways to define the relationship between a Python class and a database table. These include:

Similar Reads

What is Declarative Mapping

This is the most common way of defining a mapping in SQLAlchemy. It involves defining a Python class and using special SQLAlchemy functions and decorators to define the columns, relationships, and other metadata of the table. This approach is simple and easy to use, and it allows you to define your mappings in a clear and concise way....

What is Classical Mapping

...