Sobes.tech
Junior

What do you know about ORM (Object-Relational Mapping)?

sobes.tech AI

Answer from AI

ORM is a programming technique that connects a database with the concepts of an object-oriented programming language. It allows working with database data as Python objects, abstracting away from SQL queries.

Main advantages of ORM:

  • Speeding up development: Allows writing less code since there is no need to manually form SQL queries.
  • Portability: ORM code can often work with different types of databases, minimizing changes when switching databases.
  • Readability and maintainability: Code becomes more understandable as it uses class and object concepts.
  • Security: Some ORM frameworks provide automatic protection against SQL injection.

Disadvantages of ORM:

  • Performance: In complex scenarios or with suboptimal use, ORM can be slower than directly written SQL queries.
  • Learning curve: Requires time to master ORM concepts.
  • Debugging complexity: Sometimes it is difficult to understand which SQL queries ORM generates.

Popular ORMs for Python:

  • SQLAlchemy: A powerful and flexible ORM that provides both a lightweight SQL toolkit and a full ORM.
  • Django ORM: The built-in ORM of the Django framework, tightly integrated with its models.

Example of using SQLAlchemy:

from sqlalchemy import create_engine, Column, Integer, String
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker

# Defining a model (represents a table in the database)
Base = declarative_base()

class User(Base):
    __tablename__ = 'users'

    id = Column(Integer, primary_key=True)
    name = Column(String)
    age = Column(Integer)

    def __repr__(self):
        return f"<User(name='{self.name}', age={self.age})>"

# Connecting to the database
engine = create_engine('sqlite:///mydatabase.db') # Example with SQLite

# Creating tables (if they do not exist)
Base.metadata.create_all(engine)

# Creating a session for database interaction
Session = sessionmaker(bind=engine)
session = Session()

# Creating a new user
new_user = User(name='Alice', age=30)
session.add(new_user)
session.commit() # Committing changes

# Retrieving a user by ID
user_from_db = session.query(User).filter_by(id=1).first()
print(user_from_db)

# Closing the session
session.close()

ORM abstracts interaction with the database, allowing focus on the application's business logic. The choice of specific ORM depends on project requirements and developer preferences.