Sobes.tech
Junior — Middle

Tell us about your experience using ORM SQLAlchemy in projects.

sobes.tech AI

Answer from AI

In my projects, I used SQLAlchemy as an ORM for working with databases in Python. This allowed me to abstract away from writing pure SQL and work with Python objects that are automatically mapped to database tables.

Key aspects of my experience:

  • Defining models using classes and declarative style.
  • Creating and executing queries using SQLAlchemy sessions.
  • Using migrations (e.g., with Alembic) to manage database schema.
  • Optimizing queries with lazy loading and eager loading of relationships.

Example of a model and query:

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

Base = declarative_base()

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

engine = create_engine('sqlite:///example.db')
Session = sessionmaker(bind=engine)
session = Session()

# Adding a user
new_user = User(name='Ivan')
session.add(new_user)
session.commit()

# Querying users
users = session.query(User).filter_by(name='Ivan').all()
print(users)

SQLAlchemy significantly simplifies working with databases and makes the code more readable and maintainable.