Sobes.tech
Junior — Middle

When should you prefer using ORM over writing direct SQL queries?

sobes.tech AI

Answer from AI

ORM (Object-Relational Mapping) should be preferred when:

  • You need to work quickly and conveniently with a database without delving into SQL details.
  • The project requires support for multiple DBMSs, and you want to abstract away from SQL dialect specifics.
  • Maintaining code cleanliness and readability is important, using an object-oriented approach.
  • Automatic management of migrations and relationships between tables is required.

However, if very complex or optimized queries are needed, or performance is critical, it is sometimes better to write direct SQL queries.

Example of using ORM in Python with SQLAlchemy:

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

Base = declarative_base()

class User(Base):
    __tablename__ = 'users'
    id = Column(Integer, primary_key=True)
    name = Column(String)

engine = create_engine('sqlite:///:memory:')
Base.metadata.create_all(engine)
Session = sessionmaker(bind=engine)
session = Session()

new_user = User(name='Alice')
session.add(new_user)
session.commit()

users = session.query(User).filter_by(name='Alice').all()
print(users)