Sobes.tech
Junior — Middle

Could you explain what ORM is and how it is used in the Python language?

sobes.tech AI

Answer from AI

ORM (Object-Relational Mapping) is a technology that allows working with a database through programming language objects rather than writing SQL queries directly.

In Python, ORM is used to simplify interaction with relational databases. Instead of writing SQL code, the developer operates with classes and objects, and ORM translates these operations into SQL queries.

An example of using ORM in Python is the SQLAlchemy or Django ORM library:

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:///example.db')
Base.metadata.create_all(engine)
Session = sessionmaker(bind=engine)
session = Session()

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

Thus, ORM makes working with data easier, making the code more readable and maintainable.