Course contentsShow
← Data Science
Lesson 1120 of 2,14528. Working with Databases from PythonFree lesson

Defining Models with Declarative Base

Creating Python classes that map to database tables using declarative_base.

Defining Models with Declarative Base

You'll learn how to create Python classes that represent database tables using SQLAlchemy's declarative system.

What Is Declarative Base?

In SQLAlchemy's ORM, you define database tables by writing Python classes that inherit from a special base class. Think of it like creating a blueprint: instead of writing SQL CREATE TABLE statements, you define a Python class where each attribute represents a column. SQLAlchemy then handles the translation between your Python objects and database rows.

The declarative_base() function creates this special parent class. Every table model you define will inherit from it, giving your classes the superpowers needed to interact with the database.

Creating Your First Model

Here's how you define a simple table as a Python class:

from sqlalchemy import Column, Integer, String
from sqlalchemy.ext.declarative import declarative_base

Base = declarative_base()

class User(Base):
    __tablename__ = 'users'
    
    id = Column(Integer, primary_key=True)
    username = Column(String(50))
    email = Column(String(100))

Let's break this down:

  • Base = declarative_base() creates your foundation class
  • User(Base) means your User class inherits database capabilities
  • __tablename__ specifies the actual table name in the database
  • Each Column defines a field with its data type and constraints

The class attributes (id, username, email) become columns in your users table. When you create a User object in Python, it maps directly to a row in that table.

Why This Matters

This approach lets you work with database records as if they were regular Python objects—you can use dot notation, type hints, and all your familiar Python tools instead of writing raw SQL strings.

Key Takeaway: Declarative Base lets you define database tables as Python classes, creating a clean mapping between your object-oriented code and relational database structure.